Restructure to monorepo (#6907)

* wip: restructure to monorepo

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* refactor create-release-pr to a package

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* build fixes

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* github workflow fixes

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* fix typo

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* add webpack-env types to core

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* fix github workflows

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* refactor/fix integration tests

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* lint fix

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* yarn run dev

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* eslint settings for vscode

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* move templates to right package

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* open-lens build fixes

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* integration test fix

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* fix nx task dependencies

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* use bash shell for unit tests in test workflow

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* fix test:unit for windows

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* fix win-ca webpack error in open-lens

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* fix win-ca webpack error in open-lens

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* fix build:app on windows

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* remove ELECTRON_BUILDER_EXTRA_ARGS

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* sync src/ from master

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* remove Makefile from core

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>
This commit is contained in:
Jari Kolehmainen authored and GitHub committed 2023-01-24 10:46:26 -08:00
1 parent 0066ca4ea2
commit 2657df2293
3321 files changed
+28699 -11447

No files matched your search

@@ -0,0 +1,660 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { AsyncFnMock } from "@async-fn/jest";
import asyncFn from "@async-fn/jest";
import { createContainer, getInjectable, getInjectionToken } from "@ogre-tools/injectable";
import type { Runnable } from "./run-many-for";
import { runManyFor } from "./run-many-for";
import { getPromiseStatus } from "../test-utils/get-promise-status";
import { runInAction } from "mobx";
import { flushPromises } from "../test-utils/flush-promises";
describe("runManyFor", () => {
describe("given no hierarchy, when running many", () => {
let runMock: AsyncFnMock<(...args: unknown[]) => Promise<void>>;
let actualPromise: Promise<void>;
beforeEach(() => {
const rootDi = createContainer("irrelevant");
runMock = asyncFn();
const someInjectionTokenForRunnables = getInjectionToken<Runnable>({
id: "some-injection-token",
});
const someInjectable = getInjectable({
id: "some-injectable",
instantiate: () => ({
id: "some-injectable",
run: () => runMock("some-call"),
}),
injectionToken: someInjectionTokenForRunnables,
});
const someOtherInjectable = getInjectable({
id: "some-other-injectable",
instantiate: () => ({
id: "some-other-injectable",
run: () => runMock("some-other-call"),
}),
injectionToken: someInjectionTokenForRunnables,
});
rootDi.register(someInjectable, someOtherInjectable);
const runMany = runManyFor(rootDi)(someInjectionTokenForRunnables);
actualPromise = runMany() as Promise<void>;
});
it("runs all runnables at the same time", () => {
expect(runMock.mock.calls).toEqual([
["some-call"],
["some-other-call"],
]);
});
it("does not resolve yet", async () => {
const promiseStatus = await getPromiseStatus(actualPromise);
expect(promiseStatus.fulfilled).toBe(false);
});
it("when all runnables resolve, resolves", async () => {
await Promise.all([runMock.resolve(), runMock.resolve()]);
expect(await actualPromise).toBe(undefined);
});
});
describe("given hierarchy that is three levels deep, when running many", () => {
let runMock: AsyncFnMock<(...args: unknown[]) => Promise<void>>;
let actualPromise: Promise<void>;
beforeEach(() => {
const di = createContainer("irrelevant");
runMock = asyncFn();
const someInjectionTokenForRunnables = getInjectionToken<Runnable>({
id: "some-injection-token",
});
const someInjectable1 = getInjectable({
id: "some-injectable-1",
instantiate: (di) => ({
id: "some-injectable-1",
run: () => runMock("third-level-run"),
runAfter: di.inject(someInjectable2),
}),
injectionToken: someInjectionTokenForRunnables,
});
const someInjectable2 = getInjectable({
id: "some-injectable-2",
instantiate: (di) => ({
id: "some-injectable-2",
run: () => runMock("second-level-run"),
runAfter: di.inject(someInjectable3),
}),
injectionToken: someInjectionTokenForRunnables,
});
const someInjectable3 = getInjectable({
id: "some-injectable-3",
instantiate: () => ({
id: "some-injectable-3",
run: () => runMock("first-level-run"),
}),
injectionToken: someInjectionTokenForRunnables,
});
di.register(someInjectable1, someInjectable2, someInjectable3);
const runMany = runManyFor(di)(someInjectionTokenForRunnables);
actualPromise = runMany() as Promise<void>;
});
it("runs first level runnables", () => {
expect(runMock.mock.calls).toEqual([["first-level-run"]]);
});
it("does not resolve yet", async () => {
const promiseStatus = await getPromiseStatus(actualPromise);
expect(promiseStatus.fulfilled).toBe(false);
});
describe("when first level runnables resolve", () => {
beforeEach(async () => {
runMock.mockClear();
await runMock.resolveSpecific(["first-level-run"]);
});
it("runs second level runnables", async () => {
expect(runMock.mock.calls).toEqual([["second-level-run"]]);
});
it("does not resolve yet", async () => {
const promiseStatus = await getPromiseStatus(actualPromise);
expect(promiseStatus.fulfilled).toBe(false);
});
describe("when second level runnables resolve", () => {
beforeEach(async () => {
runMock.mockClear();
await runMock.resolveSpecific(["second-level-run"]);
});
it("runs final third level runnables", async () => {
expect(runMock.mock.calls).toEqual([["third-level-run"]]);
});
it("does not resolve yet", async () => {
const promiseStatus = await getPromiseStatus(actualPromise);
expect(promiseStatus.fulfilled).toBe(false);
});
describe("when final third level runnables resolve", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["third-level-run"]);
});
it("resolves", async () => {
const promiseStatus = await getPromiseStatus(actualPromise);
expect(promiseStatus.fulfilled).toBe(true);
});
});
});
});
});
it("given invalid hierarchy, when running runnables, throws", () => {
const rootDi = createContainer("irrelevant");
const runMock = asyncFn<(...args: unknown[]) => void>();
const someInjectionToken = getInjectionToken<Runnable>({
id: "some-injection-token",
});
const someOtherInjectionToken = getInjectionToken<Runnable>({
id: "some-other-injection-token",
});
const someInjectable = getInjectable({
id: "some-runnable-1",
instantiate: (di) => ({
id: "some-runnable-1",
run: () => runMock("some-runnable-1"),
runAfter: di.inject(someOtherInjectable),
}),
injectionToken: someInjectionToken,
});
const someOtherInjectable = getInjectable({
id: "some-runnable-2",
instantiate: () => ({
id: "some-runnable-2",
run: () => runMock("some-runnable-2"),
}),
injectionToken: someOtherInjectionToken,
});
rootDi.register(someInjectable, someOtherInjectable);
const runMany = runManyFor(rootDi)(
someInjectionToken,
);
return expect(() => runMany()).rejects.toThrow(
/Runnable "some-runnable-1" is unreachable for injection token "some-injection-token": run afters "some-runnable-2" are a part of different injection tokens./,
);
});
it("given partially incorrect hierarchy, when running runnables, throws", () => {
const rootDi = createContainer("irrelevant");
const runMock = asyncFn<(...args: unknown[]) => void>();
const someInjectionToken = getInjectionToken<Runnable>({
id: "some-injection-token",
});
const someOtherInjectionToken = getInjectionToken<Runnable>({
id: "some-other-injection-token",
});
const someInjectable = getInjectable({
id: "some-runnable-1",
instantiate: (di) => ({
id: "some-runnable-1",
run: () => runMock("some-runnable-1"),
runAfter: [
di.inject(someOtherInjectable),
di.inject(someSecondInjectable),
],
}),
injectionToken: someInjectionToken,
});
const someSecondInjectable = getInjectable({
id: "some-runnable-2",
instantiate: () => ({
id: "some-runnable-2",
run: () => runMock("some-runnable-2"),
}),
injectionToken: someInjectionToken,
});
const someOtherInjectable = getInjectable({
id: "some-runnable-3",
instantiate: () => ({
id: "some-runnable-3",
run: () => runMock("some-runnable-3"),
}),
injectionToken: someOtherInjectionToken,
});
rootDi.register(someInjectable, someOtherInjectable, someSecondInjectable);
const runMany = runManyFor(rootDi)(
someInjectionToken,
);
return expect(() => runMany()).rejects.toThrow(
/Runnable "some-runnable-3" is not part of the injection token "some-injection-token"/,
);
});
describe("when running many with parameter", () => {
let runMock: AsyncFnMock<(...args: unknown[]) => Promise<void>>;
beforeEach(() => {
const rootDi = createContainer("irrelevant");
runMock = asyncFn();
const someInjectionTokenForRunnablesWithParameter = getInjectionToken<
Runnable<string>
>({
id: "some-injection-token",
});
const someInjectable = getInjectable({
id: "some-runnable-1",
instantiate: () => ({
id: "some-runnable-1",
run: (parameter) => runMock("run-of-some-runnable-1", parameter),
}),
injectionToken: someInjectionTokenForRunnablesWithParameter,
});
const someOtherInjectable = getInjectable({
id: "some-runnable-2",
instantiate: () => ({
id: "some-runnable-2",
run: (parameter) => runMock("run-of-some-runnable-2", parameter),
}),
injectionToken: someInjectionTokenForRunnablesWithParameter,
});
rootDi.register(someInjectable, someOtherInjectable);
const runMany = runManyFor(rootDi)(
someInjectionTokenForRunnablesWithParameter,
);
runMany("some-parameter");
});
it("runs all runnables using the parameter", () => {
expect(runMock.mock.calls).toEqual([
["run-of-some-runnable-1", "some-parameter"],
["run-of-some-runnable-2", "some-parameter"],
]);
});
});
describe("given multiple runAfters", () => {
let runMock: AsyncFnMock<(...args: unknown[]) => void>;
let finishingPromise: Promise<void>;
beforeEach(async () => {
const rootDi = createContainer("irrelevant");
runMock = asyncFn<(...args: unknown[]) => void>();
const someInjectionToken = getInjectionToken<Runnable>({
id: "some-injection-token",
});
const runnableOneInjectable = getInjectable({
id: "runnable-1",
instantiate: () => ({
id: "runnable-1",
run: () => runMock("runnable-1"),
}),
injectionToken: someInjectionToken,
});
const runnableTwoInjectable = getInjectable({
id: "runnable-2",
instantiate: () => ({
id: "runnable-2",
run: () => runMock("runnable-2"),
runAfter: [], // shouldn't block being called
}),
injectionToken: someInjectionToken,
});
const runnableThreeInjectable = getInjectable({
id: "runnable-3",
instantiate: (di) => ({
id: "runnable-3",
run: () => runMock("runnable-3"),
runAfter: di.inject(runnableOneInjectable),
}),
injectionToken: someInjectionToken,
});
const runnableFourInjectable = getInjectable({
id: "runnable-4",
instantiate: (di) => ({
id: "runnable-4",
run: () => runMock("runnable-4"),
runAfter: [di.inject(runnableThreeInjectable)], // should be the same as an single item
}),
injectionToken: someInjectionToken,
});
const runnableFiveInjectable = getInjectable({
id: "runnable-5",
instantiate: (di) => ({
id: "runnable-5",
run: () => runMock("runnable-5"),
runAfter: di.inject(runnableThreeInjectable),
}),
injectionToken: someInjectionToken,
});
const runnableSixInjectable = getInjectable({
id: "runnable-6",
instantiate: (di) => ({
id: "runnable-6",
run: () => runMock("runnable-6"),
runAfter: [
di.inject(runnableFourInjectable),
di.inject(runnableFiveInjectable),
],
}),
injectionToken: someInjectionToken,
});
const runnableSevenInjectable = getInjectable({
id: "runnable-7",
instantiate: (di) => ({
id: "runnable-7",
run: () => runMock("runnable-7"),
runAfter: [
di.inject(runnableFiveInjectable),
di.inject(runnableSixInjectable),
],
}),
injectionToken: someInjectionToken,
});
runInAction(() => {
rootDi.register(
runnableOneInjectable,
runnableTwoInjectable,
runnableThreeInjectable,
runnableFourInjectable,
runnableFiveInjectable,
runnableSixInjectable,
runnableSevenInjectable,
);
});
const runMany = runManyFor(rootDi);
const runSome = runMany(someInjectionToken);
finishingPromise = runSome();
await flushPromises();
});
it("should run 'runnable-1'", () => {
expect(runMock).toBeCalledWith("runnable-1");
});
it("should run 'runnable-2'", () => {
expect(runMock).toBeCalledWith("runnable-2");
});
it("should not run 'runnable-3'", () => {
expect(runMock).not.toBeCalledWith("runnable-3");
});
describe("when 'runnable-1' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-1"]);
});
it("should run 'runnable-3'", () => {
expect(runMock).toBeCalledWith("runnable-3");
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(3);
});
});
describe("when 'runnable-3' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-3"]);
});
it("should run 'runnable-4'", () => {
expect(runMock).toBeCalledWith("runnable-4");
});
it("should run 'runnable-5'", () => {
expect(runMock).toBeCalledWith("runnable-5");
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(5);
});
});
describe("when 'runnable-4' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-4"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(5);
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(5);
});
});
describe("when 'runnable-5' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-5"]);
});
it("should run 'runnable-6'", () => {
expect(runMock).toBeCalledWith("runnable-6");
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(6);
});
});
describe("when 'runnable-6' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-6"]);
});
it("should run 'runnable-7'", () => {
expect(runMock).toBeCalledWith("runnable-7");
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(7);
});
describe("when 'runnable-7' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-7"]);
});
it("should resolve the runMany promise call", async () => {
await finishingPromise;
});
});
});
});
});
});
describe("when 'runnable-5' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-5"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(5);
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(5);
});
});
describe("when 'runnable-4' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-4"]);
});
it("should run 'runnable-6'", () => {
expect(runMock).toBeCalledWith("runnable-6");
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(6);
});
});
describe("when 'runnable-6' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-6"]);
});
it("should run 'runnable-7'", () => {
expect(runMock).toBeCalledWith("runnable-7");
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(7);
});
describe("when 'runnable-7' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-7"]);
});
it("should resolve the runMany promise call", async () => {
await finishingPromise;
});
});
});
});
});
});
});
});
describe("when 'runnable-2' resolves", () => {
beforeEach(async () => {
await runMock.resolveSpecific(["runnable-2"]);
});
it("shouldn't call any more runnables", () => {
expect(runMock).toBeCalledTimes(2);
});
});
});
});
@@ -0,0 +1,140 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { DiContainerForInjection, InjectionToken } from "@ogre-tools/injectable";
import type { SingleOrMany } from "../utils";
import { getOrInsert, getOrInsertSetFor, isDefined } from "../utils";
import * as uuid from "uuid";
import assert from "assert";
import type { Asyncify } from "type-fest";
import type TypedEventEmitter from "typed-emitter";
import EventEmitter from "events";
export interface Runnable<TParameter = void> {
id: string;
run: Run<TParameter>;
runAfter?: SingleOrMany<Runnable<TParameter>>;
}
type Run<Param> = (parameter: Param) => Promise<void> | void;
export type RunMany = <Param>(injectionToken: InjectionToken<Runnable<Param>, void>) => Asyncify<Run<Param>>;
const computedNextEdge = (traversed: string[], graph: Map<string, Set<string>>, currentId: string, seenIds: Set<string>) => {
seenIds.add(currentId);
const currentNode = graph.get(currentId);
assert(currentNode, `Runnable graph does not contain node with id="${currentId}"`);
for (const nextId of currentNode.values()) {
if (traversed.includes(nextId)) {
throw new Error(`Cycle in runnable graph: "${traversed.join(`" -> "`)}" -> "${nextId}"`);
}
computedNextEdge([...traversed, nextId], graph, nextId, seenIds);
}
};
const verifyRunnablesAreDAG = <Param>(injectionToken: InjectionToken<Runnable<Param>, void>, runnables: Runnable<Param>[]) => {
const rootId = uuid.v4();
const runnableGraph = new Map<string, Set<string>>();
const seenIds = new Set<string>();
const addRunnableId = getOrInsertSetFor(runnableGraph);
// Build the Directed graph
for (const runnable of runnables) {
addRunnableId(runnable.id);
if (!runnable.runAfter || (Array.isArray(runnable.runAfter) && runnable.runAfter.length === 0)) {
addRunnableId(rootId).add(runnable.id);
} else if (Array.isArray(runnable.runAfter)) {
for (const parentRunnable of runnable.runAfter) {
addRunnableId(parentRunnable.id).add(runnable.id);
}
} else {
addRunnableId(runnable.runAfter.id).add(runnable.id);
}
}
addRunnableId(rootId);
// Do a DFS to find any cycles
computedNextEdge([], runnableGraph, rootId, seenIds);
for (const id of runnableGraph.keys()) {
if (!seenIds.has(id)) {
const runnable = runnables.find(runnable => runnable.id === id);
if (!runnable) {
throw new Error(`Runnable "${id}" is not part of the injection token "${injectionToken.id}"`);
}
const runAfters = [runnable.runAfter]
.flat()
.filter(isDefined)
.map(runnable => runnable.id)
.join('", "');
throw new Error(`Runnable "${id}" is unreachable for injection token "${injectionToken.id}": run afters "${runAfters}" are a part of different injection tokens.`);
}
}
};
interface BarrierEvent {
finish: (id: string) => void;
}
class DynamicBarrier {
private readonly finishedIds = new Map<string, Promise<void>>();
private readonly events: TypedEventEmitter<BarrierEvent> = new EventEmitter();
private initFinishingPromise(id: string): Promise<void> {
return getOrInsert(this.finishedIds, id, new Promise(resolve => {
const handler = (finishedId: string) => {
if (finishedId === id) {
resolve();
this.events.removeListener("finish", handler);
}
};
this.events.addListener("finish", handler);
}));
}
setFinished(id: string): void {
void this.initFinishingPromise(id);
this.events.emit("finish", id);
}
async blockOn(id: string): Promise<void> {
await this.initFinishingPromise(id);
}
}
const executeRunnableWith = <Param>(param: Param) => {
const barrier = new DynamicBarrier();
return async (runnable: Runnable<Param>): Promise<void> => {
const parentRunnables = [runnable.runAfter].flat().filter(isDefined);
for (const parentRunnable of parentRunnables) {
await barrier.blockOn(parentRunnable.id);
}
await runnable.run(param);
barrier.setFinished(runnable.id);
};
};
export function runManyFor(di: DiContainerForInjection): RunMany {
return <Param>(injectionToken: InjectionToken<Runnable<Param>, void>) => async (param: Param) => {
const executeRunnable = executeRunnableWith(param);
const allRunnables = di.injectMany(injectionToken);
verifyRunnablesAreDAG(injectionToken, allRunnables);
await Promise.all(allRunnables.map(executeRunnable));
};
}
@@ -0,0 +1,212 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { createContainer, getInjectable, getInjectionToken } from "@ogre-tools/injectable";
import type { RunnableSync } from "./run-many-sync-for";
import { runManySyncFor } from "./run-many-sync-for";
describe("runManySyncFor", () => {
describe("given hierarchy, when running many", () => {
let runMock: jest.Mock;
beforeEach(() => {
const rootDi = createContainer("irrelevant");
runMock = jest.fn();
const someInjectionTokenForRunnables = getInjectionToken<RunnableSync>({
id: "some-injection-token",
});
const someInjectable = getInjectable({
id: "some-injectable",
instantiate: () => ({
id: "some-injectable",
run: () => runMock("some-call"),
}),
injectionToken: someInjectionTokenForRunnables,
});
const someOtherInjectable = getInjectable({
id: "some-other-injectable",
instantiate: () => ({
id: "some-other-injectable",
run: () => runMock("some-other-call"),
}),
injectionToken: someInjectionTokenForRunnables,
});
rootDi.register(someInjectable, someOtherInjectable);
const runMany = runManySyncFor(rootDi)(someInjectionTokenForRunnables);
runMany();
});
it("runs all runnables at the same time", () => {
expect(runMock.mock.calls).toEqual([
["some-call"],
["some-other-call"],
]);
});
});
describe("given hierarchy that is three levels deep, when running many", () => {
let runMock: jest.Mock<(arg: string) => void>;
beforeEach(() => {
const di = createContainer("irrelevant");
runMock = jest.fn();
const someInjectionTokenForRunnables = getInjectionToken<RunnableSync>({
id: "some-injection-token",
});
const someInjectable1 = getInjectable({
id: "some-injectable-1",
instantiate: (di) => ({
id: "some-injectable-1",
run: () => void runMock("third-level-run"),
runAfter: di.inject(someInjectable2),
}),
injectionToken: someInjectionTokenForRunnables,
});
const someInjectable2 = getInjectable({
id: "some-injectable-2",
instantiate: (di) => ({
id: "some-injectable-2",
run: () => void runMock("second-level-run"),
runAfter: di.inject(someInjectable3),
}),
injectionToken: someInjectionTokenForRunnables,
});
const someInjectable3 = getInjectable({
id: "some-injectable-3",
instantiate: () => ({
id: "some-injectable-3",
run: () => void runMock("first-level-run"),
}),
injectionToken: someInjectionTokenForRunnables,
});
di.register(someInjectable1, someInjectable2, someInjectable3);
const runMany = runManySyncFor(di)(someInjectionTokenForRunnables);
runMany();
});
it("runs runnables in order", () => {
expect(runMock.mock.calls).toEqual([["first-level-run"], ["second-level-run"], ["third-level-run"]]);
});
});
it("given invalid hierarchy, when running runnables, throws", () => {
const rootDi = createContainer("irrelevant");
const runMock = jest.fn();
const someInjectionToken = getInjectionToken<RunnableSync>({
id: "some-injection-token",
});
const someOtherInjectionToken = getInjectionToken<RunnableSync>({
id: "some-other-injection-token",
});
const someInjectable = getInjectable({
id: "some-runnable-1",
instantiate: (di) => ({
id: "some-runnable-1",
run: () => runMock("some-runnable-1"),
runAfter: di.inject(someOtherInjectable),
}),
injectionToken: someInjectionToken,
});
const someOtherInjectable = getInjectable({
id: "some-runnable-2",
instantiate: () => ({
id: "some-runnable-2",
run: () => runMock("some-runnable-2"),
}),
injectionToken: someOtherInjectionToken,
});
rootDi.register(someInjectable, someOtherInjectable);
const runMany = runManySyncFor(rootDi)(
someInjectionToken,
);
return expect(() => runMany()).toThrow(
/Tried to get a composite but encountered missing parent ids: "some-runnable-2".\n\nAvailable parent ids are:\n"[0-9a-z-]+",\n"some-runnable-1"/,
);
});
describe("when running many with parameter", () => {
let runMock: jest.Mock<(arg: string, arg2: string) => undefined>;
beforeEach(() => {
const rootDi = createContainer("irrelevant");
runMock = jest.fn();
const someInjectionTokenForRunnablesWithParameter = getInjectionToken<
RunnableSync<string>
>({
id: "some-injection-token",
});
const someInjectable = getInjectable({
id: "some-runnable-1",
instantiate: () => ({
id: "some-runnable-1",
run: (parameter) => void runMock("run-of-some-runnable-1", parameter),
}),
injectionToken: someInjectionTokenForRunnablesWithParameter,
});
const someOtherInjectable = getInjectable({
id: "some-runnable-2",
instantiate: () => ({
id: "some-runnable-2",
run: (parameter) => void runMock("run-of-some-runnable-2", parameter),
}),
injectionToken: someInjectionTokenForRunnablesWithParameter,
});
rootDi.register(someInjectable, someOtherInjectable);
const runMany = runManySyncFor(rootDi)(
someInjectionTokenForRunnablesWithParameter,
);
runMany("some-parameter");
});
it("runs all runnables using the parameter", () => {
expect(runMock.mock.calls).toEqual([
["run-of-some-runnable-1", "some-parameter"],
["run-of-some-runnable-2", "some-parameter"],
]);
});
});
});
@@ -0,0 +1,55 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { DiContainerForInjection, InjectionToken } from "@ogre-tools/injectable";
import type { Composite } from "../utils/composite/get-composite/get-composite";
import { getCompositeFor } from "../utils/composite/get-composite/get-composite";
import * as uuid from "uuid";
export interface RunnableSync<TParameter = void> {
id: string;
run: RunSync<TParameter>;
runAfter?: RunnableSync<TParameter>;
}
/**
* NOTE: this is the worse of two evils. This makes sure that `RunnableSync` always is sync.
* If the return type is `void` instead then async functions (those return `Promise<T>`) can
* coerce to it.
*/
type RunSync<Param> = (parameter: Param) => undefined;
export type RunManySync = <Param>(injectionToken: InjectionToken<RunnableSync<Param>, void>) => RunSync<Param>;
function runCompositeRunnableSyncs<Param>(param: Param, composite: Composite<RunnableSync<Param>>): undefined {
composite.value.run(param);
composite.children.map(composite => runCompositeRunnableSyncs(param, composite));
return undefined;
}
export function runManySyncFor(di: DiContainerForInjection): RunManySync {
return <Param>(injectionToken: InjectionToken<RunnableSync<Param>, void>) => (param: Param): undefined => {
const allRunnables = di.injectMany(injectionToken);
const rootId = uuid.v4();
const getCompositeRunnables = getCompositeFor<RunnableSync<Param>>({
getId: (runnable) => runnable.id,
getParentId: (runnable) => (
runnable.id === rootId
? undefined
: runnable.runAfter?.id ?? rootId
),
});
const composite = getCompositeRunnables([
// This is a dummy runnable to conform to the requirements of `getCompositeFor` to only have one root
{
id: rootId,
run: () => undefined,
},
...allRunnables,
]);
return runCompositeRunnableSyncs(param, composite);
};
}