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: improvements #169

Merged
Merged
Show file tree
Hide file tree
Changes from 6 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
Binary file modified bun.lockb
Binary file not shown.
9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
"typings": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"require": "./dist/index.js",
"import": "./dist/index.mjs"
"types": "./dist/index.d.ts",
"require": "./dist/index.js",
"import": "./dist/index.mjs"
}
},
"files": [
Expand Down Expand Up @@ -53,6 +53,7 @@
"@cfworker/json-schema": "2.0.1",
"@octokit/auth-app": "7.1.0",
"@octokit/core": "6.1.2",
"@octokit/plugin-paginate-graphql": "^5.2.4",
"@octokit/plugin-paginate-rest": "11.3.3",
"@octokit/plugin-rest-endpoint-methods": "13.2.4",
"@octokit/plugin-retry": "7.1.1",
Expand All @@ -61,7 +62,7 @@
"@octokit/types": "^13.5.0",
"@octokit/webhooks": "13.3.0",
"@octokit/webhooks-types": "7.5.1",
"@sinclair/typebox": "0.32.35",
"@sinclair/typebox": "^0.33.17",
"@ubiquity-os/ubiquity-os-logger": "^1.3.2",
"dotenv": "16.4.5",
"hono": "4.4.13",
Expand Down
2 changes: 2 additions & 0 deletions src/github/handlers/push-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ async function checkPluginConfigurations(context: GitHubContext<"push">, config:
value: JSON.stringify(plugin),
type: 0,
schema: configSchema,
errors: [],
});
} else {
const validator = new Validator(manifest.configuration, "7", false);
Expand All @@ -113,6 +114,7 @@ async function checkPluginConfigurations(context: GitHubContext<"push">, config:
value: JSON.stringify(value),
type: 0,
schema: configSchema,
errors: [],
});
}
}
Expand Down
68 changes: 62 additions & 6 deletions src/sdk/actions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as core from "@actions/core";
import * as github from "@actions/github";
import { EmitterWebhookEventName as WebhookEventName } from "@octokit/webhooks";
import { Type as T, TAnySchema } from "@sinclair/typebox";
import { TAnySchema, Type as T } from "@sinclair/typebox";
import { Value } from "@sinclair/typebox/value";
import { LOG_LEVEL, LogLevel, LogReturn, Logs } from "@ubiquity-os/ubiquity-os-logger";
import { config } from "dotenv";
Expand Down Expand Up @@ -31,6 +31,8 @@ const inputSchema = T.Object({
signature: T.String(),
});

const HEADER_NAME = "Ubiquity";

export async function createActionsPlugin<TConfig = unknown, TEnv = unknown, TSupportedEvents extends WebhookEventName = WebhookEventName>(
handler: (context: Context<TConfig, TEnv, TSupportedEvents>) => Promise<Record<string, unknown> | undefined>,
options?: Options
Expand All @@ -55,14 +57,24 @@ export async function createActionsPlugin<TConfig = unknown, TEnv = unknown, TSu

let config: TConfig;
if (pluginOptions.settingsSchema) {
config = Value.Decode(pluginOptions.settingsSchema, Value.Default(pluginOptions.settingsSchema, JSON.parse(inputs.settings)));
try {
config = Value.Decode(pluginOptions.settingsSchema, Value.Default(pluginOptions.settingsSchema, JSON.parse(inputs.settings)));
} catch (e) {
console.dir(...Value.Errors(pluginOptions.settingsSchema, JSON.parse(inputs.settings)), { depth: null });
throw e;
}
} else {
config = JSON.parse(inputs.settings) as TConfig;
}

let env: TEnv;
if (pluginOptions.envSchema) {
env = Value.Decode(pluginOptions.envSchema, Value.Default(pluginOptions.envSchema, process.env));
try {
env = Value.Decode(pluginOptions.envSchema, Value.Default(pluginOptions.envSchema, process.env));
} catch (e) {
console.dir(...Value.Errors(pluginOptions.envSchema, process.env), { depth: null });
throw e;
}
} else {
env = process.env as TEnv;
}
Expand Down Expand Up @@ -96,12 +108,12 @@ export async function createActionsPlugin<TConfig = unknown, TEnv = unknown, TSu
}

if (pluginOptions.postCommentOnError && loggerError) {
await postComment(context, loggerError);
await postErrorComment(context, loggerError);
}
}
}

async function postComment(context: Context, error: LogReturn) {
async function postErrorComment(context: Context, error: LogReturn) {
gentlementlegen marked this conversation as resolved.
Show resolved Hide resolved
gentlementlegen marked this conversation as resolved.
Show resolved Hide resolved
if ("issue" in context.payload && context.payload.repository?.owner?.login) {
await context.octokit.rest.issues.createComment({
owner: context.payload.repository.owner.login,
Expand All @@ -110,7 +122,7 @@ async function postComment(context: Context, error: LogReturn) {
body: `${error.logMessage.diff}\n<!--\n${getGithubWorkflowRunUrl()}\n${sanitizeMetadata(error.metadata)}\n-->`,
});
} else {
context.logger.info("Cannot post comment because issue is not found in the payload");
context.logger.info("Cannot post error comment because issue is not found in the payload");
}
}

Expand All @@ -130,3 +142,47 @@ async function returnDataToKernel(repoToken: string, stateId: string, output: ob
},
});
}

function createStructuredMetadata(className: string | undefined, logReturn: LogReturn) {
gentlementlegen marked this conversation as resolved.
Show resolved Hide resolved
gentlementlegen marked this conversation as resolved.
Show resolved Hide resolved
let logMessage, metadata;
if (logReturn) {
logMessage = logReturn.logMessage;
metadata = logReturn.metadata;
}

const jsonPretty = sanitizeMetadata(metadata);
const stackLine = new Error().stack?.split("\n")[2] ?? "";
gentlementlegen marked this conversation as resolved.
Show resolved Hide resolved
const caller = stackLine.match(/at (\S+)/)?.[1] ?? "";
const ubiquityMetadataHeader = `<!-- ${HEADER_NAME} - ${className} - ${caller} - ${metadata?.revision}`;
gentlementlegen marked this conversation as resolved.
Show resolved Hide resolved
gentlementlegen marked this conversation as resolved.
Show resolved Hide resolved

let metadataSerialized: string;
const metadataSerializedVisible = ["```json", jsonPretty, "```"].join("\n");
const metadataSerializedHidden = [ubiquityMetadataHeader, jsonPretty, "-->"].join("\n");

if (logMessage?.type === "fatal") {
// if the log message is fatal, then we want to show the metadata
metadataSerialized = [metadataSerializedVisible, metadataSerializedHidden].join("\n");
} else {
// otherwise we want to hide it
metadataSerialized = metadataSerializedHidden;
}

return metadataSerialized;
}

/**
* Posts a comment on a GitHub issue if the issue exists in the context payload, embedding structured metadata to it.
*/
export async function postComment(context: Context, message: LogReturn) {
if ("issue" in context.payload && context.payload.repository?.owner?.login) {
const metadata = createStructuredMetadata(message.metadata?.name, message);
await context.octokit.rest.issues.createComment({
owner: context.payload.repository.owner.login,
repo: context.payload.repository.name,
issue_number: context.payload.issue.number,
body: [message.logMessage.raw, metadata].join("\n"),
});
} else {
context.logger.info("Cannot post comment because issue is not found in the payload");
}
}
3 changes: 2 additions & 1 deletion src/sdk/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { createPlugin } from "./server";
export { createActionsPlugin } from "./actions";
export { createActionsPlugin, postComment } from "./actions";
export type { Context } from "./context";
export * from "./constants";
export type { Manifest } from "../types/manifest";
3 changes: 2 additions & 1 deletion src/sdk/octokit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { paginateRest } from "@octokit/plugin-paginate-rest";
import { restEndpointMethods } from "@octokit/plugin-rest-endpoint-methods";
import { retry } from "@octokit/plugin-retry";
import { throttling } from "@octokit/plugin-throttling";
import { paginateGraphQL } from "@octokit/plugin-paginate-graphql";

const defaultOptions = {
throttle: {
Expand All @@ -22,6 +23,6 @@ const defaultOptions = {
},
};

export const customOctokit = Octokit.plugin(throttling, retry, paginateRest, restEndpointMethods).defaults((instanceOptions: object) => {
export const customOctokit = Octokit.plugin(throttling, retry, paginateRest, restEndpointMethods, paginateGraphQL).defaults((instanceOptions: object) => {
return Object.assign({}, defaultOptions, instanceOptions);
});
15 changes: 13 additions & 2 deletions src/sdk/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { Context } from "./context";
import { customOctokit } from "./octokit";
import { verifySignature } from "./signature";
import { sanitizeMetadata } from "./util";
import { env as honoEnv } from "hono/adapter";

interface Options {
kernelPublicKey?: string;
Expand Down Expand Up @@ -52,14 +53,24 @@ export async function createPlugin<TConfig = unknown, TEnv = unknown, TSupported

let config: TConfig;
if (pluginOptions.settingsSchema) {
config = Value.Decode(pluginOptions.settingsSchema, Value.Default(pluginOptions.settingsSchema, payload.settings));
try {
config = Value.Decode(pluginOptions.settingsSchema, Value.Default(pluginOptions.settingsSchema, payload.settings));
} catch (e) {
console.dir(...Value.Errors(pluginOptions.settingsSchema, payload.settings), { depth: null });
throw e;
}
} else {
config = payload.settings as TConfig;
}

let env: TEnv;
if (pluginOptions.envSchema) {
env = Value.Decode(pluginOptions.envSchema, Value.Default(pluginOptions.envSchema, ctx.env));
try {
env = Value.Decode(pluginOptions.envSchema, Value.Default(pluginOptions.envSchema, honoEnv(ctx)));
} catch (e) {
console.dir(...Value.Errors(pluginOptions.envSchema, ctx.env), { depth: null });
throw e;
}
} else {
env = ctx.env as TEnv;
}
Expand Down