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

[DRAFT] Golem plugins #875

Draft
wants to merge 3 commits into
base: beta
Choose a base branch
from
Draft
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
70 changes: 70 additions & 0 deletions src/plugins/examplePlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { MarketApi } from "ya-ts-client";
import { GolemPlugin, registerGlobalPlugin } from "./pluginManager";
import { LocalPluginManager } from "./localPluginManager";

// plugin that will be registered globally
const linearPricingOnlyPlugin: GolemPlugin = {
name: "linearPricingOnlyPlugin",
version: "1.0.0",
register(golem) {
golem.market.registerHook("beforeDemandPublished", (demand) => {
demand.properties["golem.com.pricing.model"] = "linear";
return demand;
});

golem.market.registerHook("filterInitialProposal", (proposal) => {
if (proposal.properties["golem.com.pricing.model"] !== "linear") {
return { isAccepted: false, reason: "Invalid pricing model" };
}
return { isAccepted: true };
});

golem.market.on("demandPublished", (demand) => {
console.log("demand has been published", demand);
});
},
};

// plugin that will be registered on a particular demand instead of globally
const cpuArchitecturePlugin: GolemPlugin = {
name: "cpuArchitecturePlugin",
version: "1.0.0",
register(golem) {
golem.market.registerHook("beforeDemandPublished", (demand) => {
demand.properties["golem.com.cpu.architecture"] = "x86_64";
return demand;
});
},
};

class Demand {
private pluginManager = new LocalPluginManager();
constructor(plugins?: GolemPlugin[]) {
if (plugins) {
plugins.forEach((plugin) => this.pluginManager.registerPlugin(plugin));
}
}

async publish() {
let demand: MarketApi.DemandDTO = {
properties: {},
} as MarketApi.DemandDTO;

const hooks = this.pluginManager.getHooks("beforeDemandPublished");
for (const hook of hooks) {
demand = await hook(demand);
}
this.pluginManager.emitEvent("demandPublished", demand);
return demand;
}
}

registerGlobalPlugin(linearPricingOnlyPlugin);
const demand0 = new Demand([cpuArchitecturePlugin]);
const demand1 = new Demand();

// 👇 this demand will have pricing model and architecture set by the plugins
const demandWithCpuArchitecture = await demand0.publish();
// 👇 this demand will have only pricing model set by the global plugin
const demandWithOnlyLinearPricing = await demand1.publish();
22 changes: 22 additions & 0 deletions src/plugins/localPluginManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import EventEmitter from "eventemitter3";
import { AllEvents, AllHooks, GlobalPluginManager, PluginManager } from "./pluginManager";

/**
* Plugin manager that will combine local and global plugins.
* Global plugins should be registered using `GlobalPluginManager`.
* Global hooks will be executed before local hooks, in order of registration.
*/
export class LocalPluginManager extends PluginManager {
getHooks<T extends keyof AllHooks>(hookName: T): AllHooks[T][] {
const localHooks = super.getHooks(hookName);
const globalHooks = GlobalPluginManager.getHooks(hookName);
return [...globalHooks, ...localHooks];
}
public emitEvent<T extends keyof AllEvents>(
eventName: T,
...args: EventEmitter.ArgumentMap<AllEvents>[Extract<T, keyof AllEvents>]
): void {
GlobalPluginManager.emitEvent(eventName, ...args);
super.emitEvent(eventName, ...args);
}
}
17 changes: 17 additions & 0 deletions src/plugins/marketPluginContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { PluginContext } from "./pluginContext";
import { MarketApi } from "ya-ts-client";
type DemandDTO = MarketApi.DemandDTO;
type ProposalDTO = MarketApi.ProposalDTO;

type OkOrNot = { isAccepted: true } | { isAccepted: false; reason: string };
export type MarketHooks = {
beforeDemandPublished: (demand: DemandDTO) => DemandDTO | Promise<DemandDTO>;
filterInitialProposal: (proposal: ProposalDTO) => OkOrNot | Promise<OkOrNot>;
};

export type MarketEvents = {
demandPublished: (demand: DemandDTO) => void;
initialProposalReceived: (proposal: ProposalDTO) => void;
};

export class MarketPluginContext extends PluginContext<MarketHooks, MarketEvents> {}
22 changes: 22 additions & 0 deletions src/plugins/pluginContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import EventEmitter from "eventemitter3";

export abstract class PluginContext<
Hooks extends { [key: string]: (...args: never[]) => unknown },
Events extends { [key: string]: (...args: never[]) => unknown },
> {
constructor(
private registerEventFn: <T extends EventEmitter.EventNames<Events>>(
eventName: T,
callback: EventEmitter.EventListener<Events, T>,
) => void,
private registerHookFn: (hookName: keyof Hooks, hook: Hooks[keyof Hooks]) => void,
) {}

registerHook<T extends keyof Hooks>(hookName: T, hook: Hooks[T]) {
this.registerHookFn(hookName, hook);
}

on<T extends EventEmitter.EventNames<Events>>(eventName: T, callback: EventEmitter.EventListener<Events, T>) {
this.registerEventFn(eventName, callback);
}
}
55 changes: 55 additions & 0 deletions src/plugins/pluginManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import EventEmitter from "eventemitter3";
import { MarketEvents, MarketHooks, MarketPluginContext } from "./marketPluginContext";

type GolemPluginContext = {
market: MarketPluginContext;
};
export type GolemPlugin = {
name: string;
version: string;
register(context: GolemPluginContext): void;
};

export type AllHooks = MarketHooks; // | DeploymentHooks | PaymentHooks | ...
export type AllEvents = MarketEvents; // | DeploymentEvents | PaymentEvents | ...

export class PluginManager {
private eventEmitter = new EventEmitter<AllEvents>();
private hooks = new Map<keyof AllHooks, AllHooks[keyof AllHooks][]>();

private registerHook<T extends keyof AllHooks>(hookName: T, hook: AllHooks[T]) {
if (!this.hooks.has(hookName)) {
this.hooks.set(hookName, []);
}
this.hooks.get(hookName)!.push(hook as NonNullable<AllHooks[T]>);
}

public registerPlugin(plugin: GolemPlugin) {
const ctx = {
market: new MarketPluginContext(
(eventName, callback) => this.eventEmitter.on(eventName, callback),
(hookName, hook) => this.registerHook(hookName, hook),
),
// deployment: ...
// payment: ...
// ...
};
plugin.register(ctx);
}
public getHooks<T extends keyof AllHooks>(hookName: T): AllHooks[T][] {
return (this.hooks.get(hookName) || []) as AllHooks[T][];
}
public emitEvent<T extends keyof AllEvents>(
eventName: T,
...args: EventEmitter.ArgumentMap<MarketEvents>[Extract<T, keyof MarketEvents>]
) {
this.eventEmitter.emit(eventName, ...args);
}
}

// eslint-disable-next-line @typescript-eslint/naming-convention
export const GlobalPluginManager = new PluginManager();

export function registerGlobalPlugin(...plugins: GolemPlugin[]) {
plugins.forEach((plugin) => GlobalPluginManager.registerPlugin(plugin));
}
Loading