Skip to content

Commit

Permalink
chore: add worker setup
Browse files Browse the repository at this point in the history
  • Loading branch information
Keyrxng committed Jun 2, 2024
1 parent be2e81b commit 626c007
Show file tree
Hide file tree
Showing 15 changed files with 128 additions and 67 deletions.
2 changes: 1 addition & 1 deletion .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"ignorePaths": ["**/*.json", "**/*.css", "node_modules", "**/*.log", "./src/adapters/supabase/**/**.ts"],
"useGitignore": true,
"language": "en",
"words": ["dataurl", "devpool", "outdir", "servedir", "Supabase", "SUPABASE", "typebox", "ubiquibot", "Smee", "buidling"],
"words": ["Nektos", "dataurl", "devpool", "outdir", "servedir", "Supabase", "SUPABASE", "typebox", "ubiquibot", "Smee", "buidling"],
"dictionaries": ["typescript", "node", "software-terms"],
"import": ["@cspell/dict-typescript/cspell-ext.json", "@cspell/dict-node/cspell-ext.json", "@cspell/dict-software-terms"],
"ignoreRegExpList": ["[0-9a-fA-F]{6}"]
Expand Down
2 changes: 2 additions & 0 deletions .dev.vars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
SUPABASE_URL=
SUPABASE_KEY=
4 changes: 2 additions & 2 deletions .github/workflows/compute.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
runs-on: ubuntu-latest
permissions: write-all
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
UBIQUIBOT_TOKEN: ${{ secrets.UBIQUIBOT_TOKEN }}
SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
SUPABASE_KEY: ${{ secrets.SUPABASE_KEY }}

Expand All @@ -41,6 +41,6 @@ jobs:
run: npx tsx ./src/main.ts
id: plugin-name
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
UBIQUIBOT_TOKEN: ${{ secrets.UBIQUIBOT_TOKEN }}
SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
SUPABASE_KEY: ${{ secrets.SUPABASE_KEY }}
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ node_modules
.pnp.cjs
.pnp.loader.mjs
.env
.env.dev
.dev.vars
static/dist
coverage
junit.xml
cypress/screenshots
script.ts
.wrangler
6 changes: 0 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,6 @@ It contains the ingredients for a basic plugin, including the necessary files an
- A basic understanding of the Ubiquibot configuration file and how to define your plugin's settings.
- A working knowledge of TypeScript and Node.js.

## Notes

- Typescript and subsequently `TSX` are used to run the plugin logic from the workflow, avoiding the need to compile to JS.
- The plugin is run in a worker context, meaning that it is run in a separate container from the kernel and has no access to the kernel's context, only the context the kernel passes to it.
- Due to the above, your plugin runs using a generalized `GITHUB_TOKEN` and not your personal access token. This means that you will not have access to private repositories across plugins (afaik), but will have access to the plugin's repository if it is private.

## Getting Started

1. Create a new repository using this template.
Expand Down
8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"knip": "knip --config .github/knip.ts",
"knip-ci": "knip --no-exit-code --reporter json --config .github/knip.ts",
"prepare": "husky install",
"test": "jest --setupFiles dotenv/config --coverage"
"test": "jest --setupFiles dotenv/config --coverage",
"worker": "wrangler dev --env dev --port 4000"
},
"keywords": [
"typescript",
Expand Down Expand Up @@ -61,7 +62,8 @@
"prettier": "^3.2.5",
"ts-jest": "29.1.2",
"tsx": "^4.7.1",
"typescript": "^5.3.3"
"typescript": "^5.3.3",
"wrangler": "3.57.0"
},
"lint-staged": {
"*.ts": [
Expand All @@ -77,4 +79,4 @@
"@commitlint/config-conventional"
]
}
}
}
7 changes: 7 additions & 0 deletions src/handlers/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Context } from "../types/context";

export async function doSomething(context: Context) {
const { logger } = context;
logger.info("Doing something");
return "Something done";
}
44 changes: 42 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,47 @@
import * as core from "@actions/core";
import plugin from "./plugin";
import * as github from "@actions/github";
import { Octokit } from "@octokit/rest";
import { Value } from "@sinclair/typebox/build/cjs/value";
import { envSchema, pluginSettingsSchema, PluginInputs } from "./types";
import { plugin } from "./plugin";

plugin()
/**
* How a GitHub action executes the plugin.
*/
export async function run() {
const payload = github.context.payload.inputs;

const env = Value.Decode(envSchema, process.env);
const settings = Value.Decode(pluginSettingsSchema, JSON.parse(payload.settings));

const inputs: PluginInputs = {
stateId: payload.stateId,
eventName: payload.eventName,
eventPayload: JSON.parse(payload.eventPayload),
settings,
authToken: env.UBIQUIBOT_TOKEN,
ref: payload.ref,
};

await plugin(inputs, env);

return returnDataToKernel(inputs.authToken, inputs.stateId, {});
}

async function returnDataToKernel(repoToken: string, stateId: string, output: object) {
const octokit = new Octokit({ auth: repoToken });
await octokit.repos.createDispatchEvent({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
event_type: "return_data_to_ubiquibot_kernel",
client_payload: {
state_id: stateId,
output: JSON.stringify(output),
},
});
}

run()
.then((result) => {
core.setOutput("result", result);
})
Expand Down
24 changes: 0 additions & 24 deletions src/plugin-config.yml

This file was deleted.

40 changes: 13 additions & 27 deletions src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,17 @@
import * as github from "@actions/github";
import { Context } from "./types/context";

import { Octokit } from "@octokit/rest";
import { Value } from "@sinclair/typebox/value";
import { createClient } from "@supabase/supabase-js";
import { createAdapters } from "./adapters";
import { Database } from "./adapters/supabase/types/database";
import { Context } from "./types/context";
import { envSchema } from "./types/env";
import { pluginSettingsSchema, PluginInputs } from "./types/plugin-inputs";
import { doSomething } from "./handlers/handler";
import { Env, PluginInputs } from "./types";

async function setup() {
const payload = github.context.payload.inputs;

const env = Value.Decode(envSchema, process.env);
const settings = Value.Decode(pluginSettingsSchema, JSON.parse(payload.settings));

const inputs: PluginInputs = {
stateId: payload.stateId,
eventName: payload.eventName,
eventPayload: JSON.parse(payload.eventPayload),
settings,
authToken: env.GITHUB_TOKEN,
ref: payload.ref,
};
/**
* How a worker executes the plugin.
*/

export async function plugin(inputs: PluginInputs, env: Env) {
const octokit = new Octokit({ auth: inputs.authToken });
const supabase = createClient<Database>(env.SUPABASE_URL, env.SUPABASE_KEY);

Expand Down Expand Up @@ -54,12 +43,9 @@ async function setup() {

context.adapters = createAdapters(supabase, context);

return context;
}

export default async function plugin() {
const context = await setup();

// Add your plugin logic here
context.logger.info("Hello, World!");
if (context.eventName === "issue_comment.created") {
await doSomething(context);
} else {
context.logger.error(`Unsupported event: ${context.eventName}`);
}
}
2 changes: 1 addition & 1 deletion src/types/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export interface Context<T extends SupportedEventsU = SupportedEventsU, TU exten
adapters: ReturnType<typeof createAdapters>;
config: PluginSettings;
env: {
GITHUB_TOKEN: string;
UBIQUIBOT_TOKEN: string;
SUPABASE_URL: string;
SUPABASE_KEY: string;
};
Expand Down
2 changes: 1 addition & 1 deletion src/types/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { StaticDecode } from "@sinclair/typebox";
import "dotenv/config";

export const envSchema = T.Object({
GITHUB_TOKEN: T.String(),
UBIQUIBOT_TOKEN: T.String(),
SUPABASE_URL: T.String(),
SUPABASE_KEY: T.String(),
});
Expand Down
4 changes: 4 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from "./context";
export * from "./env";
export * from "./plugin-inputs";
export * from "./github";
39 changes: 39 additions & 0 deletions src/worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Value } from "@sinclair/typebox/value";
import { plugin } from "./plugin";
import { Env } from "./types/env";
import { pluginSettingsSchema } from "./types";

export default {
async fetch(request: Request, env: Env): Promise<Response> {
try {
if (request.method !== "POST") {
return new Response(JSON.stringify({ error: `Only POST requests are supported.` }), {
status: 405,
headers: { "content-type": "application/json", Allow: "POST" },
});
}
const contentType = request.headers.get("content-type");
if (contentType !== "application/json") {
return new Response(JSON.stringify({ error: `Error: ${contentType} is not a valid content type` }), {
status: 400,
headers: { "content-type": "application/json" },
});
}

const webhookPayload = await request.json();
const settings = Value.Decode(pluginSettingsSchema, Value.Default(pluginSettingsSchema, JSON.parse(webhookPayload.settings)));
webhookPayload.eventPayload = JSON.parse(webhookPayload.eventPayload);
webhookPayload.settings = settings;
await plugin(webhookPayload, env);
return new Response(JSON.stringify("OK"), { status: 200, headers: { "content-type": "application/json" } });
} catch (error) {
return handleUncaughtError(error);
}
},
};

function handleUncaughtError(error: unknown) {
console.error(error);
const status = 500;
return new Response(JSON.stringify({ error }), { status: status, headers: { "content-type": "application/json" } });
}
7 changes: 7 additions & 0 deletions wrangler.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
name = "your-plugin-name"
main = "src/worker.ts"
compatibility_date = "2024-05-23"
node_compat = true

[env.dev]
[env.prod]

0 comments on commit 626c007

Please sign in to comment.