Skip to content

Commit

Permalink
refactor: replace wait with setTimeout from node:timers/promises (
Browse files Browse the repository at this point in the history
  • Loading branch information
AlCalzone authored Oct 28, 2024
1 parent 5cd50f5 commit cd90c09
Show file tree
Hide file tree
Showing 66 changed files with 174 additions and 82 deletions.
2 changes: 1 addition & 1 deletion packages/cc/src/cc/Security2CC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ import type {
GetValueDB,
} from "@zwave-js/host/safe";
import { buffer2hex, getEnumMemberName, pick } from "@zwave-js/shared/safe";
import { wait } from "alcalzone-shared/async";
import { isArray } from "alcalzone-shared/typeguards";
import { setTimeout as wait } from "node:timers/promises";
import { CCAPI } from "../lib/API";
import {
type CCRaw,
Expand Down
2 changes: 1 addition & 1 deletion packages/cc/src/cc/SecurityCC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ import type {
GetValueDB,
} from "@zwave-js/host/safe";
import { buffer2hex, num2hex, pick } from "@zwave-js/shared/safe";
import { wait } from "alcalzone-shared/async";
import { randomBytes } from "node:crypto";
import { setTimeout as wait } from "node:timers/promises";
import { CCAPI, PhysicalCCAPI } from "../lib/API";
import {
type CCRaw,
Expand Down
2 changes: 1 addition & 1 deletion packages/config/maintenance/lintConfigFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ import {
num2hex,
} from "@zwave-js/shared";
import { distinct } from "alcalzone-shared/arrays";
import { wait } from "alcalzone-shared/async";
import { isArray, isObject } from "alcalzone-shared/typeguards";
import { green, red, white } from "ansi-colors";
import levenshtein from "js-levenshtein";
import type { RulesLogic } from "json-logic-js";
import * as path from "node:path";
import { setTimeout as wait } from "node:timers/promises";
import type { ConditionalParamInfoMap, ParamInfoMap } from "../src";
import { ConfigManager } from "../src/ConfigManager";
import { parseLogic } from "../src/Logic";
Expand Down
2 changes: 1 addition & 1 deletion packages/flash/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ZWaveErrorCodes, isZWaveError } from "@zwave-js/core/safe";
import { wait } from "alcalzone-shared/async";
import fs from "fs-extra";
import path from "node:path";
import { setTimeout as wait } from "node:timers/promises";
import yargs from "yargs";
import {
ControllerFirmwareUpdateStatus,
Expand Down
88 changes: 88 additions & 0 deletions packages/maintenance/src/refactorWait.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import fs from "node:fs/promises";
import { Project, SyntaxKind } from "ts-morph";

async function main() {
const project = new Project({
tsConfigFilePath: "packages/zwave-js/tsconfig.json",
});

const sourceFiles = project.getSourceFiles();
for (const file of sourceFiles) {
const waitImports = file.getImportDeclarations().filter((i) =>
i.getModuleSpecifierValue() === "alcalzone-shared/async"
).map((i) => {
const named = i.getNamedImports().find((n) =>
n.getName() === "wait"
);
if (!named) return;
return [i, named] as const;
}).filter((i) => i != undefined);

for (const [decl, named] of waitImports) {
decl.setModuleSpecifier("node:timers/promises");
named.replaceWithText("setTimeout as wait");
}

const waitCalls = file.getDescendantsOfKind(SyntaxKind.CallExpression)
.filter((c) =>
c.getExpressionIfKind(SyntaxKind.Identifier)?.getText()
=== "wait"
)
.map((c) => {
const args = c.getArguments();
if (args.length < 1 || args.length > 2) return;
const timeout = args[0];
const unref = args[1]?.getText() as string | undefined;
const then = c.getParentIfKind(
SyntaxKind.PropertyAccessExpression,
);
const thenCall = then?.getName() === "then"
&& then.getParentIfKind(SyntaxKind.CallExpression);
const thenArg = thenCall && thenCall.getArguments()[0];
const thenResult = thenArg
&& thenArg.asKind(SyntaxKind.ArrowFunction)?.getBodyText();
const nodeToReplace = thenResult ? thenCall : c;

return [
nodeToReplace,
timeout.getText(),
thenResult || "undefined",
unref,
] as const;
})
.filter((c) => c != undefined);

for (const [node, timeout, thenResult, unref] of waitCalls) {
const ref = unref === "true"
? "false"
: !!unref
? `!${unref}`
: "true";
if (ref === "true") {
if (thenResult === "undefined") {
node.replaceWithText(`wait(${timeout})`);
} else {
node.replaceWithText(
`wait(${timeout}, ${thenResult})`,
);
}
} else {
node.replaceWithText(
`wait(${timeout}, ${thenResult}, { ref: ${ref} })`,
);
}
}

await file.save();
}
}

void main().catch(async (e) => {
await fs.writeFile(`${e.filePath}.old`, e.oldText);
await fs.writeFile(`${e.filePath}.new`, e.newText);
console.error(`Error refactoring file ${e.filePath}
old text: ${e.filePath}.old
new text: ${e.filePath}.new`);

process.exit(1);
});
2 changes: 1 addition & 1 deletion packages/serial/src/serialport/ZWaveSerialPort.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { wait } from "alcalzone-shared/async";
import ava, { type TestFn } from "ava";
import { PassThrough } from "node:stream";
import { setTimeout as wait } from "node:timers/promises";
import sinon from "sinon";
import { MessageHeaders } from "../message/MessageHeaders";
import { createAndOpenMockedZWaveSerialPort } from "../mock/MockSerialPort";
Expand Down
2 changes: 1 addition & 1 deletion packages/shared/src/AsyncQueue.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { wait } from "alcalzone-shared/async";
import test from "ava";
import { setTimeout as wait } from "node:timers/promises";
import { AsyncQueue } from "./AsyncQueue";

test("can be iterated over after adding items", async (t) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/testing/src/MockController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ import {
import type { MockPortBinding } from "@zwave-js/serial/mock";
import { AsyncQueue } from "@zwave-js/shared";
import { TimedExpectation } from "@zwave-js/shared/safe";
import { wait } from "alcalzone-shared/async";
import { randomInt } from "node:crypto";
import { setTimeout as wait } from "node:timers/promises";
import {
type MockControllerCapabilities,
getDefaultMockControllerCapabilities,
Expand Down
8 changes: 4 additions & 4 deletions packages/zwave-js/src/lib/controller/Controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,14 +370,14 @@ import {
pick,
} from "@zwave-js/shared";
import { distinct } from "alcalzone-shared/arrays";
import { wait } from "alcalzone-shared/async";
import {
type DeferredPromise,
createDeferredPromise,
} from "alcalzone-shared/deferred-promise";
import { roundTo } from "alcalzone-shared/math";
import { isObject } from "alcalzone-shared/typeguards";
import crypto from "node:crypto";
import { setTimeout as wait } from "node:timers/promises";
import type { Driver } from "../driver/Driver";
import { cacheKeyUtils, cacheKeys } from "../driver/NetworkCache";
import type { StatisticsEventCallbacks } from "../driver/Statistics";
Expand Down Expand Up @@ -3221,7 +3221,7 @@ export class ZWaveController

for (const task of tasks) {
const result = await Promise.race([
wait(S0_TIMEOUT, true).then(() => false as const),
wait(S0_TIMEOUT, false as const, { ref: false }),
task().catch(() => false as const),
]);
if (result === false) {
Expand Down Expand Up @@ -3500,7 +3500,7 @@ export class ZWaveController

// TODO: Validate client-side auth if requested
const grantResult = await Promise.race([
wait(inclusionTimeouts.TAI1, true).then(() => false as const),
wait(inclusionTimeouts.TAI1, false as const, { ref: false }),
userCallbacks
.grantSecurityClasses({
securityClasses: supportedKeys,
Expand Down Expand Up @@ -3597,7 +3597,7 @@ export class ZWaveController
pinResult = inclusionOptions.dsk.slice(0, 5);
} else {
pinResult = await Promise.race([
wait(tai2RemainingMs, true).then(() => false as const),
wait(tai2RemainingMs, false as const, { ref: false }),
userCallbacks
.validateDSKAndEnterPIN(dsk)
// ignore errors in application callbacks
Expand Down
9 changes: 5 additions & 4 deletions packages/zwave-js/src/lib/driver/Driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,6 @@ import {
pick,
} from "@zwave-js/shared";
import { distinct } from "alcalzone-shared/arrays";
import { wait } from "alcalzone-shared/async";
import {
type DeferredPromise,
createDeferredPromise,
Expand All @@ -190,6 +189,7 @@ import { randomBytes } from "node:crypto";
import type { EventEmitter } from "node:events";
import os from "node:os";
import path from "node:path";
import { setTimeout as wait } from "node:timers/promises";
import { URL } from "node:url";
import * as util from "node:util";
import { SerialPort } from "serialport";
Expand Down Expand Up @@ -2746,7 +2746,7 @@ export class Driver extends TypedEventEmitter<DriverEventCallbacks>
`Firmware updated. No restart or re-interview required. Refreshing version information in ${waitTime} seconds...`,
);

await wait(waitTime * 1000, true);
await wait(waitTime * 1000, undefined, { ref: false });

try {
const versionAPI = node.commandClasses.Version;
Expand Down Expand Up @@ -5676,7 +5676,8 @@ ${handlers.length} left`,
);
await wait(
this.options.timeouts.retryJammed,
true,
undefined,
{ ref: false },
);

continue attemptMessage;
Expand Down Expand Up @@ -7284,7 +7285,7 @@ ${handlers.length} left`,
this._enterBootloaderPromise = createDeferredPromise();
const success = await Promise.race([
this._enterBootloaderPromise.then(() => true),
wait(5000, true).then(() => false),
wait(5000, false, { ref: false }),
]);
if (success) {
this.controllerLog.print("Entered bootloader");
Expand Down
6 changes: 3 additions & 3 deletions packages/zwave-js/src/lib/driver/MessageGenerators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@ import {
} from "@zwave-js/serial/serialapi";
import { type ContainsCC, containsCC } from "@zwave-js/serial/serialapi";
import { getErrorMessage } from "@zwave-js/shared";
import { wait } from "alcalzone-shared/async";
import {
type DeferredPromise,
createDeferredPromise,
} from "alcalzone-shared/deferred-promise";
import { setTimeout as wait } from "node:timers/promises";
import type { Driver } from "./Driver";
import type { MessageGenerator } from "./Transaction";

Expand Down Expand Up @@ -332,7 +332,7 @@ export const maybeTransportServiceGenerator: MessageGeneratorImplementation<
if (isFirstTransferredSegment) {
isFirstTransferredSegment = false;
} else if (segmentDelay) {
await wait(segmentDelay, true);
await wait(segmentDelay, undefined, { ref: false });
}
const segment = unsentSegments.shift()!;

Expand Down Expand Up @@ -409,7 +409,7 @@ export const maybeTransportServiceGenerator: MessageGeneratorImplementation<
level: "debug",
});

await wait(waitTime, true);
await wait(waitTime, undefined, { ref: false });
continue attempts;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/zwave-js/src/lib/driver/Task.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ZWaveError, ZWaveErrorCodes, assertZWaveError } from "@zwave-js/core";
import { noop } from "@zwave-js/shared";
import { wait } from "alcalzone-shared/async";
import { createDeferredPromise } from "alcalzone-shared/deferred-promise";
import test from "ava";
import { setTimeout as wait } from "node:timers/promises";
import {
type TaskBuilder,
TaskInterruptBehavior,
Expand Down
4 changes: 2 additions & 2 deletions packages/zwave-js/src/lib/node/Node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,6 @@ import {
pick,
stringify,
} from "@zwave-js/shared";
import { wait } from "alcalzone-shared/async";
import {
type DeferredPromise,
createDeferredPromise,
Expand All @@ -234,6 +233,7 @@ import { padStart } from "alcalzone-shared/strings";
import { isArray, isObject } from "alcalzone-shared/typeguards";
import { EventEmitter } from "node:events";
import path from "node:path";
import { setTimeout as wait } from "node:timers/promises";
import semver from "semver";
import { RemoveNodeReason } from "../controller/Inclusion";
import { determineNIF } from "../controller/NodeInformationFrame";
Expand Down Expand Up @@ -5914,7 +5914,7 @@ ${formatRouteHealthCheckSummary(this.id, otherNode.id, summary)}`,
options.interval - (Date.now() - lastStart),
);
await Promise.race([
wait(waitDurationMs, true),
wait(waitDurationMs, undefined, { ref: false }),
this._abortLinkReliabilityCheckPromise,
]);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/zwave-js/src/lib/node/VirtualEndpoint.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import {
import { FunctionType } from "@zwave-js/serial";
import type { MockSerialPort } from "@zwave-js/serial/mock";
import type { ThrowingMap } from "@zwave-js/shared";
import { wait } from "alcalzone-shared/async";
import ava, { type ExecutionContext, type TestFn } from "ava";
import { setTimeout as wait } from "node:timers/promises";
import { ZWaveController } from "../controller/Controller";
import type { Driver } from "../driver/Driver";
import { createAndStartDriver } from "../test/utils";
Expand Down
7 changes: 5 additions & 2 deletions packages/zwave-js/src/lib/node/mixins/70_FirmwareUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ import {
import { containsCC } from "@zwave-js/serial/serialapi";
import { getEnumMemberName, throttle } from "@zwave-js/shared";
import { distinct } from "alcalzone-shared/arrays";
import { wait } from "alcalzone-shared/async";
import {
type DeferredPromise,
createDeferredPromise,
} from "alcalzone-shared/deferred-promise";
import { roundTo } from "alcalzone-shared/math";
import { randomBytes } from "node:crypto";
import { setTimeout as wait } from "node:timers/promises";
import { type Task, type TaskBuilder, TaskPriority } from "../../driver/Task";
import { type Transaction } from "../../driver/Transaction";
import { SchedulePollMixin } from "./60_ScheduledPoll";
Expand Down Expand Up @@ -465,7 +465,10 @@ export abstract class FirmwareUpdateMixin extends SchedulePollMixin
// If we've resumed the previous file, there's no need to resume the next one too
shouldResume = false;

yield () => wait(conservativeWaitTime * 1000, true);
yield () =>
wait(conservativeWaitTime * 1000, undefined, {
ref: false,
});
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import {
RateType,
} from "@zwave-js/cc";
import { createMockZWaveRequestFrame } from "@zwave-js/testing";
import { wait } from "alcalzone-shared/async";
import path from "node:path";
import { setTimeout as wait } from "node:timers/promises";
import { integrationTest } from "../integrationTestSuite";

integrationTest(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { DoorLockMode } from "@zwave-js/cc";
import { DoorLockCCValues } from "@zwave-js/cc/DoorLockCC";
import { NotificationCCReport } from "@zwave-js/cc/NotificationCC";
import { createMockZWaveRequestFrame } from "@zwave-js/testing";
import { wait } from "alcalzone-shared/async";
import path from "node:path";
import { setTimeout as wait } from "node:timers/promises";
import { integrationTest } from "../integrationTestSuite";

integrationTest(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
} from "@zwave-js/cc/NotificationCC";
import { CommandClasses, type ValueMetadataNumeric } from "@zwave-js/core";
import { createMockZWaveRequestFrame } from "@zwave-js/testing";
import { wait } from "alcalzone-shared/async";
import { setTimeout as wait } from "node:timers/promises";
import { integrationTest } from "../integrationTestSuite";

integrationTest(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import {
NotificationCCValues,
} from "@zwave-js/cc/NotificationCC";
import { createMockZWaveRequestFrame } from "@zwave-js/testing";
import { wait } from "alcalzone-shared/async";
import path from "node:path";
import { setTimeout as wait } from "node:timers/promises";
import { integrationTest } from "../integrationTestSuite";

integrationTest("Notification values can get idled manually", {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import {
NotificationCCValues,
} from "@zwave-js/cc/NotificationCC";
import { createMockZWaveRequestFrame } from "@zwave-js/testing";
import { wait } from "alcalzone-shared/async";
import path from "node:path";
import { setTimeout as wait } from "node:timers/promises";
import { integrationTest } from "../integrationTestSuite";

integrationTest(
Expand Down
Loading

0 comments on commit cd90c09

Please sign in to comment.