forked from ubiquity/ubiquibot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent.ts
More file actions
263 lines (229 loc) · 8.83 KB
/
Copy pathevent.ts
File metadata and controls
263 lines (229 loc) · 8.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import OpenAI from "openai";
import { Context as ProbotContext } from "probot";
import { LogReturn, Logs } from "ubiquibot-logger";
import zlib from "zlib";
import { createAdapters, supabaseClient } from "../adapters/adapters";
import { processors, wildcardProcessors } from "../handlers/processors";
import { validateConfigChange } from "../handlers/push/push";
import structuredMetadata from "../handlers/shared/structured-metadata";
import { BotConfig } from "../types/configuration-types";
import { addCommentToIssue } from "../helpers/issue";
import { shouldSkip } from "../helpers/shared";
import { Context } from "../types/context";
import {
HandlerReturnValuesNoVoid,
MainActionHandler,
PostActionHandler,
PreActionHandler,
WildCardHandler,
} from "../types/handlers";
import { GitHubEvent, GitHubPayload, payloadSchema } from "../types/payload";
import { ajv } from "../utils/ajv";
import { generateConfiguration } from "../utils/generate-configuration";
import Runtime from "./bot-runtime";
import { env } from "./env";
const allowedEvents = Object.values(GitHubEvent) as string[];
const NO_VALIDATION = [GitHubEvent.INSTALLATION_ADDED_EVENT, GitHubEvent.PUSH_EVENT] as string[];
type PreHandlerWithType = { type: string; actions: PreActionHandler[] };
type HandlerWithType = { type: string; actions: MainActionHandler[] };
type WildCardHandlerWithType = { type: string; actions: WildCardHandler[] };
type PostHandlerWithType = { type: string; actions: PostActionHandler[] };
type AllHandlersWithTypes = PreHandlerWithType | HandlerWithType | PostHandlerWithType;
type AllHandlers = PreActionHandler | MainActionHandler | PostActionHandler;
const validatePayload = ajv.compile(payloadSchema);
const runtime = Runtime.getState();
runtime.adapters = createAdapters();
runtime.logger = runtime.adapters.supabase.logs;
export async function bindEvents(eventContext: ProbotContext) {
const payload = eventContext.payload as GitHubPayload;
const eventName = payload?.action ? `${eventContext.name}.${payload?.action}` : eventContext.name; // some events wont have actions as this grows
const logger = new Logs(supabaseClient, env.LOG_RETRY_LIMIT, env.LOG_LEVEL, eventContext);
logger.info("Event received", { id: eventContext.id, name: eventName });
if (!allowedEvents.includes(eventName) && eventContext.name !== "repository_dispatch") {
// just check if its on the watch list
return logger.info(`Skipping the event. reason: not configured`);
}
// Skip validation for installation event and push
if (!NO_VALIDATION.includes(eventName)) {
// Validate payload
const isValid = validatePayload(payload);
if (!isValid && validatePayload.errors) {
return logger.error("Payload schema validation failed!", validatePayload.errors);
}
// Check if we should skip the event
const should = shouldSkip(eventContext);
if (should.stop) {
return logger.info("Skipping the event.", { reason: should.reason });
}
}
if (eventName === GitHubEvent.PUSH_EVENT) {
await validateConfigChange(eventContext);
}
let botConfig: BotConfig;
try {
botConfig = await generateConfiguration(eventContext);
} catch (error) {
return;
}
const context: Context = {
event: eventContext,
config: botConfig,
openAi: botConfig.keys.openAi ? new OpenAI({ apiKey: botConfig.keys.openAi }) : null,
logger: logger,
payload: payload,
octokit: eventContext.octokit,
};
if (!context.config.keys.evmPrivateEncrypted) {
context.logger.error("No EVM private key found");
}
if (!context.logger) {
throw new Error("Failed to create logger");
}
if (eventContext.name === GitHubEvent.REPOSITORY_DISPATCH) {
const dispatchPayload = payload as any;
if (payload.action === "issueClosed") {
//This is response for issueClosed request
const response = dispatchPayload.client_payload.result;
if (response) {
const uncompressedComment = zlib.gunzipSync(Buffer.from(response));
await addCommentToIssue(
context,
uncompressedComment.toString(),
parseInt(dispatchPayload.client_payload.issueNumber)
);
}
}
}
// Get the handlers for the action
const handlers = processors[eventName];
if (!handlers) {
return context.logger.error("No handler configured for event:", { eventName });
}
const { pre, action, post } = handlers;
const handlerWithTypes: AllHandlersWithTypes[] = [
{ type: "pre", actions: pre },
{ type: "main", actions: action },
{ type: "post", actions: post },
];
for (const handlerWithType of handlerWithTypes) {
// List all the function names of handlerType.actions
const functionNames = handlerWithType.actions.map((action) => action?.name);
context.logger.info(
`Running "${handlerWithType.type}" \
for event: "${eventName}". \
handlers: "${functionNames.join(", ")}"`
);
await logAnyReturnFromHandlers(context, handlerWithType);
}
// Skip wildcard handlers for installation event and push event
if (eventName == GitHubEvent.INSTALLATION_ADDED_EVENT || eventName == GitHubEvent.PUSH_EVENT) {
return context.logger.info("Skipping wildcard handlers for event:", eventName);
} else {
// Run wildcard handlers
const functionNames = wildcardProcessors.map((action) => action?.name);
context.logger.info(`Running wildcard handlers: "${functionNames.join(", ")}"`);
const wildCardHandlerType: WildCardHandlerWithType = { type: "wildcard", actions: wildcardProcessors };
await logAnyReturnFromHandlers(context, wildCardHandlerType);
}
}
async function logAnyReturnFromHandlers(context: Context, handlerType: AllHandlersWithTypes) {
for (const action of handlerType.actions) {
const renderCatchAllWithContext = createRenderCatchAll(context, handlerType, action);
try {
// checkHandler(action);
const response = await action(context);
if (handlerType.type === "main") {
// only log main handler results
await renderMainActionOutput(context, response, action);
} else {
// context.logger.ok("Completed", { action: action.name, type: handlerType.type });
}
} catch (report: unknown) {
await renderCatchAllWithContext(report);
}
}
}
async function renderMainActionOutput(
context: Context,
response: void | HandlerReturnValuesNoVoid,
action: AllHandlers
) {
const { payload, logger } = context;
const issueNumber = payload.issue?.number;
if (!issueNumber) {
throw new Error("No issue number found");
}
if (response instanceof LogReturn) {
let serializedComment;
if (response.metadata) {
serializedComment = [
response.logMessage.diff,
structuredMetadata.create(response.logMessage.type, response.metadata),
].join("\n");
} else {
serializedComment = response.logMessage.diff;
}
await addCommentToIssue(context, serializedComment, issueNumber);
} else if (typeof response == "string") {
await addCommentToIssue(context, response, issueNumber);
} else if (response === null) {
logger.debug("null response", { action: action.name });
} else {
logger.error(
"No response from action. Ensure return of string, null, or LogReturn object",
{ action: action.name },
true
);
}
}
function createRenderCatchAll(context: Context, handlerType: AllHandlersWithTypes, activeHandler: AllHandlers) {
return async function renderCatchAll(report: LogReturn | Error | unknown) {
const payload = context.event.payload as GitHubPayload;
const issue = payload.issue;
if (!issue) {
return context.logger.error("Issue is null. Skipping", { issue });
}
if (report instanceof LogReturn) {
// already made it to console so it should just post the comment
if (report.metadata) {
return await addCommentToIssue(
context,
[report.logMessage.diff, structuredMetadata.create(report.logMessage.type, report.metadata)].join("\n"),
issue.number
);
} else {
return await addCommentToIssue(context, report.logMessage.diff, issue.number);
}
} else if (report instanceof Error) {
// convert error to normal object
// this is now handled inside of the logger
// TODO: test this
// const error = {
// name: report.name,
// message: report.message,
// stack: report.stack,
// };
return context.logger.error(
"action has an uncaught error",
{
handlerType,
activeHandler: activeHandler.name,
error: report,
},
true
);
} else {
// could be supabase error
// report as SupabaseError
return context.logger.error(
"action returned an unexpected value",
{
logReturn: report,
handlerType,
activeHandler: activeHandler.name,
},
true
);
}
};
}