Skip to content
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
11 changes: 11 additions & 0 deletions .changeset/fast-bobcats-pay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"@plutolang/simulator-adapter": patch
"@plutolang/static-generator": patch
"@plutolang/pulumi-adapter": patch
"@plutolang/pluto-infra": patch
"@plutolang/pluto": patch
"@plutolang/base": patch
"@plutolang/cli": patch
---

feat: instantiate resource infrastructure classes asynchronously within the base class of each resource
3 changes: 3 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.pluto/
dist/
node_modules/
6 changes: 6 additions & 0 deletions apps/cli/src/commands/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,12 @@ async function testOneGroup(
}
} else {
const testers = listAllTester(applyResult.outputs!);
if (testers.length === 0) {
console.warn("Not found any testers.");
if (process.env.DEBUG) {
console.log("The resource of deployment: ", JSON.stringify(applyResult, undefined, 2));
}
}
for (const tester of testers) {
const testerClient = buildTesterClient(tmpSta, tester);
await testerClient.runTests();
Expand Down
7 changes: 1 addition & 6 deletions components/adapters/pulumi/src/pulumi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,7 @@ export class PulumiAdapter extends core.Adapter {
}

const result = await pulumiStack.up();

const outputs: Record<string, any> = {};
for (const key in result.outputs) {
outputs[key] = result.outputs[key].value;
}
return { outputs };
return { outputs: result.outputs["default"].value };
} catch (e) {
if (e instanceof Error) {
throw new Error("Met error during run 'pulumi update', " + e.message);
Expand Down
27 changes: 12 additions & 15 deletions components/adapters/simulator/src/simulator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { arch, simulator, Registry, runtime, engine } from "@plutolang/base";
import { arch, simulator } from "@plutolang/base";
import http from "http";

const SIM_HANDLE_PATH = "/call";
Expand All @@ -12,35 +12,32 @@ export class Simulator implements simulator.IContext {
this.resources = new Map();

process.env["RUNTIME_TYPE"] = "SIMULATOR";
process.env["ENGINE_TYPE"] = "simulator";
}

public async loadApp(archRef: arch.Architecture): Promise<void> {
const pkgName = "@plutolang/pluto";
const plutoClient = await import(pkgName);
const plutoInfra = await import(pkgName + "-infra");

const reg: Registry = new Registry();
plutoInfra.register(reg);

for (const resourceName in archRef.resources) {
const resource = archRef.resources[resourceName];
const resourceType = resource.type;
if (resourceType === "Root") continue;

const targetClass = resourceType === "FnResource" ? resourceType : plutoClient[resourceType];
if (!targetClass) {
throw new Error("Cannot find resource type " + resourceType);
const resourceInfraClass =
resourceType === "FnResource" ? plutoInfra["Function"] : plutoInfra[resourceType];
if (!resourceInfraClass) {
throw new Error(
"Cannot find the infrastructure implementation class of the resource type " + resourceType
);
}

const resourceInfraClass = reg.getResourceDef(
runtime.Type.Simulator,
engine.Type.simulator,
targetClass
);

const args = new Array(resource.parameters.length);
resource.parameters.forEach((param) => (args[param.index] = JSON.parse(param.value)));
const instance = new resourceInfraClass(args[0], args[1]) as simulator.IResourceInstance;
const instance = (await resourceInfraClass.createInstance(
args[0],
args[1]
)) as simulator.IResourceInstance;
await instance.setup(this);
this.registerInstance(args[0], instance);
}
Expand Down
67 changes: 35 additions & 32 deletions components/generators/static/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,36 +60,20 @@ function compileTs(code: string): string {
}

function genPirCode(archRef: arch.Architecture, projectName: string, stackName: string): string {
let iacSource = `// Register all IaC SDK
import { Registry } from "@plutolang/base";

const RUNTIME_TYPE = process.env['RUNTIME_TYPE'];
if (!RUNTIME_TYPE) {
throw new Error("Missing RUNTIME_TYPE");
}
const ENGINE_TYPE = process.env['ENGINE_TYPE'];
if (!ENGINE_TYPE) {
throw new Error("Missing ENGINE_TYPE");
}
const reg: Registry = new Registry();

import { register as plutoRegister } from "@plutolang/pluto-infra";
plutoRegister(reg);


let resDefCls;

`;
const outputVars = [];
let iacSource = "";

// Resource definition, first for BaaS, second for FaaS
for (const resName in archRef.resources) {
const res = archRef.getResource(resName);
if (res.type == "Root" || res.type == "FnResource") continue;

iacSource += res.getImports().join("\n") + "\n";

iacSource += `resDefCls = reg.getResourceDef(RUNTIME_TYPE, ENGINE_TYPE, ${res.type});
const ${resName} = new resDefCls(${res.getParamString()});\n\n`;
// TODO: choose the correct package that specified by the user.
iacSource += `
const ${resName} = await (
await import("@plutolang/pluto-infra")
).${res.type}.createInstance(${res.getParamString()});\n
`;
}

// Specify the dependency of FaaS on this particular BaaS, because the building image process needs to be performed after exporting Dapr YAML.
Expand All @@ -115,10 +99,20 @@ const ${resName} = new resDefCls(${res.getParamString()});\n\n`;
}
}

iacSource += `resDefCls = reg.getResourceDef(RUNTIME_TYPE, ENGINE_TYPE, "${res.type}");
const ${resName} = new resDefCls(${res.getParamString()}, {
envs: {${envVars.join(",\n")}}
}, { dependsOn: [${deps.join(",")}] });\n\n`;
// TODO: choose the correct package that specified by the user.
iacSource += `
const ${resName} = await (
await import("@plutolang/pluto-infra")
).Function.createInstance(
${res.getParamString()},
{
envs: {${envVars.join(",\n")}}
},
{
dependsOn: [${deps.join(",")}]
}
);\n
`;
}

// Establish resource dependencies, including triggering and accessing.
Expand All @@ -142,15 +136,24 @@ const ${resName} = new resDefCls(${res.getParamString()}, {
// TODO: update the output mechanism
if (res.type == "Router" && !outputed) {
outputed = true;
iacSource += `export const { url } = ${res.name};\n`;
outputVars.push(`url: ${res.name}.url`);
}
if (res.type == "Tester") {
iacSource += `const ${res.name}Out = ${res.name}.outputs;
export { ${res.name}Out };\n`;
iacSource += `const ${res.name}Out = ${res.name}.outputs;\n`;
outputVars.push(`${res.name}Out`);
}
}

return iacSource;
return `
export default (async () => {
${iacSource}

// The return values are the outputs of the resources.
return {
${outputVars.join(",\n")}
}
})()
`;
}

interface ComputeIR {
Expand Down
4 changes: 0 additions & 4 deletions packages/base/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,3 @@ export enum Type {
export function isRuntimeType(value: any): value is Type {
return Object.values(Type).includes(value);
}

export function same(b: string, a: Type): boolean {
return a == b.toUpperCase();
}
33 changes: 23 additions & 10 deletions packages/base/src/utils/configuration.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { homedir } from "os";
import { join } from "path";
import * as engine from "../engine";
import * as runtime from "../runtime";

/**
* Returns the path to the global configuration directory.
Expand All @@ -8,18 +10,29 @@ export function systemConfigDir(): string {
return join(homedir(), ".pluto");
}

export function currentProjectName(): string {
const projectName = process.env["PLUTO_PROJECT_NAME"];
if (!projectName) {
throw new Error("The environment variable PLUTO_PROJECT_NAME is not set.");
export const currentProjectName = () => fetchEnvWithThrow("PLUTO_PROJECT_NAME");
export const currentStackName = () => fetchEnvWithThrow("PLUTO_STACK_NAME");

export function currentPlatformType(): runtime.Type {
const val = fetchEnvWithThrow("RUNTIME_TYPE");
if (runtime.isRuntimeType(val)) {
return val;
}
throw new Error(`The '${val}' is not a valid platform type.`);
}

export function currentEngineType(): engine.Type {
const val = fetchEnvWithThrow("ENGINE_TYPE");
if (engine.isEngineType(val)) {
return val;
}
return projectName;
throw new Error(`The '${val}' is not a valid engine type.`);
}

export function currentStackName(): string {
const stackName = process.env["PLUTO_STACK_NAME"];
if (!stackName) {
throw new Error("The environment variable PLUTO_STACK_NAME is not set.");
function fetchEnvWithThrow(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`The environment variable ${name} is not set.`);
}
return stackName;
return value;
}
4 changes: 2 additions & 2 deletions packages/pluto-infra/src/aws/cloudWatchSchedule.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
import { IResource, ResourceInfra } from "@plutolang/base";
import { ScheduleInfra } from "@plutolang/pluto";
import { IScheduleInfraApi } from "@plutolang/pluto";
import { ScheduleInfraOptions } from "@plutolang/pluto/dist/schedule";
import { Lambda } from "./lambda";

export class CloudWatchSchedule
extends pulumi.ComponentResource
implements ScheduleInfra, ResourceInfra
implements IScheduleInfraApi, ResourceInfra
{
readonly name: string;

Expand Down
7 changes: 5 additions & 2 deletions packages/pluto-infra/src/aws/dynamoKVStore.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import * as aws from "@pulumi/aws";
import * as pulumi from "@pulumi/pulumi";
import { ResourceInfra } from "@plutolang/base";
import { KVStoreInfra, KVStoreInfraOptions } from "@plutolang/pluto";
import { IKVStoreInfraApi, KVStoreInfraOptions } from "@plutolang/pluto";
import { Permission } from "./permission";

export enum DynamoDbOps {
GET = "get",
SET = "set",
}

export class DynamoKVStore extends pulumi.ComponentResource implements ResourceInfra, KVStoreInfra {
export class DynamoKVStore
extends pulumi.ComponentResource
implements ResourceInfra, IKVStoreInfraApi
{
readonly name: string;
arn: pulumi.Output<string>;

Expand Down
4 changes: 2 additions & 2 deletions packages/pluto-infra/src/aws/snsQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { assert } from "console";
import * as aws from "@pulumi/aws";
import * as pulumi from "@pulumi/pulumi";
import { IResource, ResourceInfra } from "@plutolang/base";
import { QueueInfra, QueueInfraOptions } from "@plutolang/pluto/dist/queue";
import { IQueueInfraApi, QueueInfraOptions } from "@plutolang/pluto/dist/queue";
import { Lambda } from "./lambda";
import { Permission } from "./permission";

export enum SNSOps {
PUSH = "push",
}

export class SNSQueue extends pulumi.ComponentResource implements ResourceInfra, QueueInfra {
export class SNSQueue extends pulumi.ComponentResource implements ResourceInfra, IQueueInfraApi {
readonly name: string;
topic: aws.sns.Topic;

Expand Down
4 changes: 2 additions & 2 deletions packages/pluto-infra/src/aws/tester.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import * as pulumi from "@pulumi/pulumi";
import { IResource, ResourceInfra } from "@plutolang/base";
import { TestCase, TesterInfra, TesterInfraOptions } from "@plutolang/pluto";
import { TestCase, ITesterInfraApi, TesterInfraOptions } from "@plutolang/pluto";
import { Lambda } from "./lambda";

export class Tester extends pulumi.ComponentResource implements TesterInfra, ResourceInfra {
export class Tester extends pulumi.ComponentResource implements ITesterInfraApi, ResourceInfra {
public readonly name: string;
private readonly description: string;
private readonly testCases: TestCase[];
Expand Down
52 changes: 52 additions & 0 deletions packages/pluto-infra/src/function.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { engine, runtime, utils } from "@plutolang/base";
import { IFunctionInfraApi, IFunctionCapturedProps, FunctionOptions } from "@plutolang/pluto";
import { ImplClassMap } from "./utils";

// Construct a type that includes all the necessary methods required to be implemented within
// the infrastructure class of a resource type.
type IFunctionInfra = IFunctionInfraApi & IFunctionCapturedProps;

// Construct a type for a class constructor. The key point is that the parameters of the constructor
// must be consistent with the client class of this resource type. Use this type to ensure that
// all implementation classes have the correct and same constructor signature.
type FunctionInfraImplClass = new (name: string, options?: FunctionOptions) => IFunctionInfra;

// Construct a map that contains all the implementation classes for this resource type.
// The final selection will be determined at runtime, and the class will be imported lazily.
const implClassMap = new ImplClassMap<IFunctionInfra, FunctionInfraImplClass>({
[engine.Type.pulumi]: {
[runtime.Type.AWS]: async () => (await import("./aws")).Lambda,
[runtime.Type.K8s]: async () => (await import("./k8s")).ServiceLambda,
},
});

/**
* This is a factory class that provides an interface to create instances of this resource type
* based on the target platform and engine.
*/
export abstract class Function {
/**
* Asynchronously creates an instance of the function infrastructure class. The parameters of this function
* must be consistent with the constructor of both the client class and infrastructure class associated
* with this resource type.
*/
public static async createInstance(
name: string,
options?: FunctionOptions
): Promise<IFunctionInfra> {
// TODO: ensure that the resource implementation class for the simulator has identical methods as those for the cloud.
if (
utils.currentPlatformType() === runtime.Type.Simulator &&
utils.currentEngineType() === engine.Type.simulator
) {
return new (await import("./simulator")).SimFunction(name, options);
}

return implClassMap.createInstanceOrThrow(
utils.currentPlatformType(),
utils.currentEngineType(),
name,
options
);
}
}
Loading