Skip to content

Commit

Permalink
util: Closer implements and accepts Disposable
Browse files Browse the repository at this point in the history
  • Loading branch information
yoursunny committed Jan 28, 2024
1 parent 37c6054 commit ec10486
Show file tree
Hide file tree
Showing 28 changed files with 96 additions and 46 deletions.
4 changes: 2 additions & 2 deletions integ/browser-tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@
"@types/webpack": "^5.28.5",
"fork-ts-checker-webpack-plugin": "^9.0.2",
"html-webpack-plugin": "^5.6.0",
"puppeteer": "^21.7.0",
"puppeteer": "^21.9.0",
"ts-loader": "^9.5.1",
"tslib": "^2.6.2",
"type-fest": "^4.10.1",
"webpack": "^5.89.0",
"webpack": "^5.90.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1"
}
Expand Down
2 changes: 1 addition & 1 deletion integ/browser-tests/test-fixture/pptr.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as path from "node:path";
import path from "node:path";
import { fileURLToPath } from "node:url";

import { console, delay } from "@ndn/util";
Expand Down
2 changes: 1 addition & 1 deletion integ/browser-tests/vitest.config.mts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { defineConfig } from "vitest/config";

export default defineConfig({
esbuild: { target: "es2022" },
test: {
deps: {
interopDefault: true,
Expand All @@ -9,7 +10,6 @@ export default defineConfig({
"tests/**/*.t.ts",
],
watch: false,
threads: false,
testTimeout: 30000,
globalSetup: "./setup-webpack.mts",
},
Expand Down
2 changes: 1 addition & 1 deletion integ/cxx-tests/test-fixture/cxxprogram.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as path from "node:path";
import path from "node:path";
import { fileURLToPath } from "node:url";

import { execa, type ExecaChildProcess, execaSync, type Options as ExecaOptions } from "execa";
Expand Down
16 changes: 9 additions & 7 deletions integ/cxx-tests/tests/keychain/verify/test.t.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,19 @@ import { execute } from "../../../test-fixture/cxxprogram";

afterEach(deleteTmpFiles);

type Row<G> = {
algo: SigningAlgorithm<any, true, G>;
genParam: G;
};
type Row<G> = [
desc: string,
algo: SigningAlgorithm<any, true, G>,
genParam: G,
];

const TABLE = ([] as Array<Row<any>>).concat(
EcCurve.Choices.map((curve) => ({ algo: ECDSA, genParam: { curve } })),
RsaModulusLength.Choices.map((modulusLength) => ({ algo: RSA, genParam: { modulusLength } })),
EcCurve.Choices.map((curve) => [`ECDSA ${curve}`, ECDSA, { curve }]),
RsaModulusLength.Choices.map((modulusLength) => [`RSA ${modulusLength}`, RSA, { modulusLength }]),
);

test.each(TABLE)("%j", async ({ algo, genParam }) => {
test.each(TABLE)("%s", async (desc, algo, genParam) => {
void desc;
const [privateKey, publicKey] = await generateSigningKey("/A", algo, genParam);
const cert = await Certificate.selfSign({ privateKey, publicKey });

Expand Down
2 changes: 1 addition & 1 deletion integ/cxx-tests/vitest.config.mts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { defineConfig } from "vitest/config";

export default defineConfig({
esbuild: { target: "es2022" },
test: {
deps: {
interopDefault: true,
Expand All @@ -9,7 +10,6 @@ export default defineConfig({
"tests/**/*.t.ts",
],
watch: false,
threads: false,
testTimeout: 30000,
},
});
2 changes: 1 addition & 1 deletion mk/edit-packagejson.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from "node:fs/promises";
import * as path from "node:path";
import path from "node:path";

const act = process.argv[2];
const publishUri = process.env.NDNTS_PUBLISH_URI ?? "https://ndnts-nightly.ndn.today";
Expand Down
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,21 @@
"test": "vitest",
"typedoc": "bash mk/typedoc.sh"
},
"packageManager": "pnpm@8.14.3",
"packageManager": "pnpm@8.15.0+sha256.fd1eab68a6d403f35cf3259c53780d70b0f14bd74e39da2f917d201f554d8665",
"devDependencies": {
"@types/node": "^20.11.6",
"@types/node": "^20.11.8",
"@types/wtfnode": "^0.7.3",
"@typescript/lib-dom": "npm:@types/web@0.0.135",
"@vitest/coverage-v8": "^1.2.1",
"@vitest/coverage-v8": "^1.2.2",
"@yoursunny/xo-config": "0.56.2",
"codedown": "^3.1.0",
"tslib": "^2.6.2",
"typedoc": "^0.25.7",
"typescript": "~5.3.3",
"vitest": "^1.2.1"
"vitest": "^1.2.2"
},
"engines": {
"node": "^18.18.0 || ^20.0.0 || ^21.0.0"
"node": "^18.18.0 || ^20.4.0 || ^21.0.0"
},
"pnpm": {
"peerDependencyRules": {
Expand Down
2 changes: 1 addition & 1 deletion packages/autoconfig/src/platform_node.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as os from "node:os";
import os from "node:os";

import type { FwFace } from "@ndn/fw";
import { splitHostPort, TcpTransport, UdpTransport } from "@ndn/node-transport";
Expand Down
3 changes: 1 addition & 2 deletions packages/autoconfig/tests/network.t.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,13 @@ async function addServerWithDelayProducer(delayDuration: number): Promise<string
}

async function addClosedServers(count = 1): Promise<string[]> {
const servers = new Closers();
using servers = new Closers();
const hostPorts: string[] = [];
for (let i = 0; i < count; ++i) {
const server = await UdpServer.create(UdpServerForwarder);
hostPorts.push(server.hostport);
servers.push(server);
}
servers.close();
return hostPorts;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/cli-common/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"@ndn/node-transport": "workspace:*",
"@ndn/packet": "workspace:*",
"@ndn/util": "workspace:*",
"dotenv": "^16.4.0",
"dotenv": "^16.4.1",
"env-var": "^7.4.1",
"tslib": "^2.6.2",
"wtfnode": "^0.9.1"
Expand Down
4 changes: 2 additions & 2 deletions packages/cli-common/src/uplinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ async function makeFace(): Promise<[face: FwFace, nfd: boolean]> {
}
}

let theUplinks: Closers | undefined;
let theUplinks: (Closers & FwFace[]) | undefined;

/** Open the uplinks specified by NDNTS_UPLINK environ. */
export async function openUplinks({ autoClose = true }: openUplinks.Options = {}): Promise<FwFace[]> {
Expand All @@ -102,7 +102,7 @@ export async function openUplinks({ autoClose = true }: openUplinks.Options = {}
preloadFromKeyChain: openKeyChain(),
});
}
theUplinks = new Closers();
theUplinks = new Closers() as (Closers & FwFace[]);
theUplinks.push(face);
if (autoClose) {
exitClosers.push(theUplinks);
Expand Down
4 changes: 2 additions & 2 deletions packages/dpdkmgmt/src/face.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { once } from "node:events";
import * as net from "node:net";
import * as path from "node:path";
import net from "node:net";
import path from "node:path";

import { Forwarder, type FwFace } from "@ndn/fw";
import { L3Face, type Transport } from "@ndn/l3face";
Expand Down
10 changes: 4 additions & 6 deletions packages/nfdmgmt/src/prefix-reg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,11 @@ class NfdPrefixReg extends ReadvertiseDestination<State> {
});
const preloadProducers = await this.preload(endpoint);

const closers = new Closers();
using closers = new Closers();
closers.push(...map(preloadProducers, ([, p]) => p), tapFace);
try {
return await f({ ...this.commandOptions, endpoint });
} finally {
closers.close();
}
// https://github.com/typescript-eslint/typescript-eslint/issues/7889
// eslint-disable-next-line @typescript-eslint/return-await
return await f({ ...this.commandOptions, endpoint });
}

private async preload(endpoint: Endpoint) {
Expand Down
2 changes: 1 addition & 1 deletion packages/node-transport/src/tcp-transport.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as net from "node:net";
import net from "node:net";

import { L3Face, StreamTransport } from "@ndn/l3face";
import type { Except } from "type-fest";
Expand Down
4 changes: 2 additions & 2 deletions packages/node-transport/src/udp-helper.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as dgram from "node:dgram";
import dgram from "node:dgram";
import { once } from "node:events";
import * as os from "node:os";
import os from "node:os";

export const DEFAULT_MTU = 65000;
const DEFAULT_UNICAST_PORT = 6363;
Expand Down
2 changes: 1 addition & 1 deletion packages/node-transport/src/unix-transport.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as net from "node:net";
import net from "node:net";

import { L3Face, StreamTransport } from "@ndn/l3face";

Expand Down
2 changes: 1 addition & 1 deletion packages/node-transport/test-fixture/net-server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { type EventEmitter, once } from "node:events";
import * as net from "node:net";
import net from "node:net";

import { tmpNameSync } from "tmp";

Expand Down
2 changes: 1 addition & 1 deletion packages/node-transport/test-fixture/udp-server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as dgram from "node:dgram";
import dgram from "node:dgram";

import { Forwarder } from "@ndn/fw";
import { L3Face, type Transport } from "@ndn/l3face";
Expand Down
2 changes: 1 addition & 1 deletion packages/packet/tests/signing.t.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import "@ndn/tlv/test-fixture/expect";

import * as crypto from "node:crypto";
import crypto from "node:crypto";

import { type Decodable, Decoder, type Encodable, Encoder } from "@ndn/tlv";
import { delay } from "@ndn/util";
Expand Down
7 changes: 5 additions & 2 deletions packages/util/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
"type": "module",
"main": "src/mod.ts",
"module": "lib/mod_browser.js",
"sideEffects": false,
"sideEffects": [
"**/polyfill*"
],
"homepage": "https://yoursunny.com/p/NDNts/",
"repository": {
"type": "git",
Expand All @@ -26,6 +28,7 @@
"types": "lib/mod.d.ts"
},
"dependencies": {
"@shigen/polyfill-symbol-dispose": "^1.0.1",
"@types/minimalistic-assert": "^1.0.3",
"minimalistic-assert": "^1.0.1",
"streaming-iterables": "^8.0.1",
Expand All @@ -39,6 +42,6 @@
"write": "^2.0.0"
},
"engines": {
"node": "^18.18.0 || ^20.0.0 || ^21.0.0"
"node": "^18.18.0 || ^20.4.0 || ^21.0.0"
}
}
18 changes: 15 additions & 3 deletions packages/util/src/closers.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
import "./polyfill_node";

export interface Closer {
close(): void;
}

/** A list of objects that can be closed or destroyed. */
export class Closers extends Array {
/** A list of objects that can be closed or disposed. */
export class Closers extends Array<Closer | Disposable | AsyncDisposable> implements Disposable {
/** Close all objects in reverse order and clear the list. */
public close = () => {
for (let i = this.length - 1; i >= 0; --i) {
this[i]!.close();
const c: any = this[i]!;
for (const key of ["close", Symbol.dispose, Symbol.asyncDispose] as const) {
if (typeof c[key] === "function") {
c[key]();
break;
}
}
}
this.splice(0, Infinity);
};

public [Symbol.dispose](): void {
this.close();
}

/** Schedule a timeout or interval to be canceled via .close(). */
public addTimeout<T extends NodeJS.Timeout | number>(t: T): T {
this.push({ close: () => clearTimeout(t) });
Expand Down
2 changes: 2 additions & 0 deletions packages/util/src/mod.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import "./polyfill_node";

import assert from "minimalistic-assert";

export { assert };
Expand Down
1 change: 1 addition & 0 deletions packages/util/src/polyfill_browser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import "@shigen/polyfill-symbol-dispose";
1 change: 1 addition & 0 deletions packages/util/src/polyfill_node.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {};
31 changes: 31 additions & 0 deletions packages/util/tests/closers.t.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
/* eslint-disable no-use-extend-native/no-use-extend-native --
* Symbol.dispose and Symbol.asyncDispose are polyfilled
**/

import { expect, test, vi } from "vitest";

import { Closers, delay } from "..";
Expand Down Expand Up @@ -47,3 +51,30 @@ test("closers", async () => {
expect(f3).not.toHaveBeenCalled();
expect(f4).not.toHaveBeenCalled();
});

test("disposable", () => {
const c0 = {
close: vi.fn<[], void>(),
[Symbol.dispose]: vi.fn<[], void>(),
[Symbol.asyncDispose]: vi.fn<[], Promise<void>>().mockResolvedValue(),
};
const c1 = {
[Symbol.dispose]: vi.fn<[], void>(),
[Symbol.asyncDispose]: vi.fn<[], Promise<void>>().mockResolvedValue(),
};
const c2 = {
[Symbol.asyncDispose]: vi.fn<[], Promise<void>>().mockResolvedValue(),
};

{
using closers = new Closers();
closers.push(c0, c1, c2);
}

expect(c0.close).toHaveBeenCalledOnce();
expect(c0[Symbol.dispose]).not.toHaveBeenCalled();
expect(c0[Symbol.asyncDispose]).not.toHaveBeenCalled();
expect(c1[Symbol.dispose]).toHaveBeenCalledOnce();
expect(c1[Symbol.asyncDispose]).not.toHaveBeenCalled();
expect(c2[Symbol.asyncDispose]).toHaveBeenCalledOnce();
});
2 changes: 1 addition & 1 deletion packages/ws-transport/test-fixture/ws-server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { once } from "node:events";
import * as http from "node:http";
import http from "node:http";
import type * as net from "node:net";

import { NetServerBase } from "@ndn/node-transport/test-fixture/net-server";
Expand Down
1 change: 1 addition & 0 deletions vitest.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ if (process.env.COVERPKG) {
}

export default defineConfig({
esbuild: { target: "es2022" },
test: {
coverage,
deps: {
Expand Down

0 comments on commit ec10486

Please sign in to comment.