Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: enhance simulator #246

Merged
merged 3 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/brown-numbers-smash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@plutolang/simulator-adapter": patch
---

feat(adapter): enable Python execution in simulator

This commit introduces the ability to execute Python within the simulator. It also adds support for parsing arguments that access captured properties or environment variables.
1 change: 1 addition & 0 deletions .changeset/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"updateInternalDependencies": "patch",
"ignore": [
"tester",
"tester-py",
"app-with-prop-access",
"chat-bot",
"daily-joke-slack",
Expand Down
7 changes: 7 additions & 0 deletions .changeset/famous-rings-vanish.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@plutolang/cli": patch
---

feat(cli): introduce `run` command

This commit adds the `run` command to the Pluto CLI. The `pluto run` command is designed to execute the Pluto app within the simulator.
5 changes: 5 additions & 0 deletions .changeset/swift-rocks-dream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@plutolang/pluto-infra": patch
---

The resource infrastructure SDK implementation has been updated to adhere to the IResourceInfra interface, unifying the implementation for both local and cloud environments. Additionally, the Website resource type is now supported in the simulator environment.
1 change: 1 addition & 0 deletions apps/cli/src/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ export { destroy } from "./destory";
export { test } from "./test";
export { newStack } from "./stack_new";
export { log } from "./log";
export { run } from "./run";
74 changes: 74 additions & 0 deletions apps/cli/src/commands/run.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import fs from "fs";
import path from "path";
import { PlatformType, ProvisionType, config, core } from "@plutolang/base";
import logger from "../log";
import { prepareStackDirs } from "../utils";
import { loadDotEnvs } from "./env";
import { loadAndDeduce } from "./compile";
import {
buildAdapterByProvisionType,
getDefaultDeducerPkg,
getDefaultEntrypoint,
loadProjectAndStack,
loadProjectRoot,
} from "./utils";

export interface RunOptions {}

export async function run(entrypoint: string) {
const projectRoot = loadProjectRoot();
const { project } = loadProjectAndStack(projectRoot);
const stack = new config.Stack("local_run", PlatformType.Simulator, ProvisionType.Simulator);

// Load the environment variables from the `.env` files.
loadDotEnvs(projectRoot, stack.name, false);

// Prepare the directories for the stack.
const { closuresDir, baseDir, stateDir } = await prepareStackDirs(projectRoot, stack.name);

// Ensure the entrypoint exist.
entrypoint = entrypoint ?? getDefaultEntrypoint(project.language);
if (!fs.existsSync(entrypoint)) {
throw new Error(`No such file, ${entrypoint}`);
}

// construct the arch ref from user code
logger.info("Generating reference architecture...");
const { archRef } = await loadAndDeduce(
getDefaultDeducerPkg(project.language),
{
project: project.name,
stack: stack,
rootpath: projectRoot,
closureDir: closuresDir,
},
[entrypoint]
);

const archRefFile = path.join(baseDir, "arch.yml");
fs.writeFileSync(archRefFile, archRef.toYaml());

// Build the adapter and deploy the stack.
const adapter = await buildAdapterByProvisionType(stack.provisionType, {
project: project.name,
rootpath: project.rootpath,
language: project.language,
stack: stack,
archRef: archRef,
entrypoint: "",
stateDir: stateDir,
});
await deployWithAdapter(adapter, stack);
}

async function deployWithAdapter(adapter: core.Adapter, stack: config.Stack) {
logger.info("Applying...");
const applyResult = await adapter.deploy();
stack.setDeployed();
logger.info("Successfully applied!");

logger.info("Here are the resource outputs:");
for (const key in applyResult.outputs) {
logger.info(`${key}:`, applyResult.outputs[key]);
}
}
12 changes: 2 additions & 10 deletions apps/cli/src/commands/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,11 +257,7 @@ class AwsTesterClient implements TesterClient {
await this.runOne(testCase);
logger.info(` ✔️ Passed`);
} catch (e) {
if (e instanceof Error) {
logger.error(" ✖️ Failed, ", e.message);
} else {
logger.error(" ✖️ Failed, ", e);
}
logger.error(" ✖️ Failed, ", e);
}
}
}
Expand Down Expand Up @@ -299,11 +295,7 @@ class SimTesterClient implements TesterClient {
await this.simClient.runTest(testCase);
logger.info(` ✔️ Passed`);
} catch (e) {
if (e instanceof Error) {
logger.error(" ✖️ Failed, ", e.message);
} else {
logger.error(" ✖️ Failed, ", e);
}
logger.error(" ✖️ Failed, ", e);
}
}
}
Expand Down
19 changes: 16 additions & 3 deletions apps/cli/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@ import * as cmd from "./commands";
import { checkUpdate, version } from "./utils";
import logger from "./log";

let exitCnt = 0;

function exitGracefully(sig: string) {
if (process.env.DEBUG) {
console.warn(`\nReceived ${sig}. Exiting...`);
console.warn(`\nReceived ${sig}.`);
}
exitCnt++;
if (exitCnt >= 2 || sig === "SIGTERM") {
console.log("\nBye~ 👋");
process.exit(1);
} else {
console.log("\nPress Ctrl+C again to exit.");
}
console.log("\nBye~ 👋");
process.exit(1);
}

process.on("SIGINT", () => exitGracefully("SIGINT"));
Expand Down Expand Up @@ -82,6 +89,12 @@ async function main() {
)
.action(cmd.test);

program
.command("run")
.description("Run the application in the local simulator environment")
.argument("[entrypoint]", "The files need to be compiled.")
.action(cmd.run);

program
.command("deploy")
.description("Deploy this project to the platform specified in the stack")
Expand Down
5 changes: 3 additions & 2 deletions components/adapters/simulator/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@
"dependencies": {
"@plutolang/base": "workspace:^",
"@plutolang/pluto": "workspace:^",
"@plutolang/pluto-infra": "workspace:^"
"@plutolang/pluto-infra": "workspace:^",
"cors": "^2.8.5"
},
"devDependencies": {
"@types/node": "^20.8.4",
"@vitest/coverage-v8": "^0.34.6",
"typescript": "^5.2.2",
"vitest": "^0.34.6"
}
}
}
31 changes: 28 additions & 3 deletions components/adapters/simulator/src/simAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,29 @@ export class SimulatorAdapter extends core.Adapter {
}

public async deploy(): Promise<core.DeployResult> {
this.simulator = new Simulator(this.rootpath);
const envs: Record<string, string> = {
PLUTO_PROJECT_NAME: this.project,
PLUTO_STACK_NAME: this.stack.name,
PLUTO_LANGUAGE_TYPE: this.language,
PLUTO_PLATFORM_TYPE: this.stack.platformType,
PLUTO_PROVISION_TYPE: this.stack.provisionType,
WORK_DIR: this.stateDir,
};

this.simulator = new Simulator(this.rootpath);
await this.simulator.start();
process.env.PLUTO_SIMULATOR_URL = this.simulator.serverUrl;
envs.PLUTO_SIMULATOR_URL = this.simulator.serverUrl;

for (const [key, value] of Object.entries(envs)) {
process.env[key] = value;
}

await this.simulator.loadApp(this.archRef);
const outputs = await this.simulator.loadApp(this.archRef);
const awaitedOutputs = await awaitNestedPromises(outputs);

return {
outputs: {
...awaitedOutputs,
simulatorServerUrl: this.simulator.serverUrl,
},
};
Expand All @@ -60,3 +74,14 @@ export class SimulatorAdapter extends core.Adapter {
throw new errors.NotImplementedError("The simulator adapter cannot be reused.");
}
}

async function awaitNestedPromises<T>(obj: T): Promise<T> {
for (const key in obj) {
if (obj[key] instanceof Promise) {
obj[key] = await obj[key];
} else if (typeof obj[key] === "object") {
obj[key] = await awaitNestedPromises(obj[key]);
}
}
return obj;
}
Loading
Loading