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: used ubiquity-os-logger for logging #19

Merged
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"@sinclair/typebox": "0.32.33",
"@supabase/supabase-js": "2.43.5",
"@ubiquity-dao/rpc-handler": "1.3.0",
"@ubiquity-os/ubiquity-os-logger": "^1.3.2",
"commander": "12.1.0",
"dotenv": "16.4.5",
"ethers": "6.13.1",
Expand Down
2 changes: 1 addition & 1 deletion src/adapters/supabase/helpers/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ export class Wallet extends Super {
if (walletData.location_id === null) {
throw new Error("Location ID is null");
}
logger.debug("Enriching wallet location metadata", locationMetaData);
logger.debug("Enriching wallet location metadata", { locationMetaData });
return this.supabase.from("locations").update(locationMetaData).eq("id", walletData.location_id);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/handlers/command-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class CommandParser {
context.logger.debug(str);
},
async writeErr(str: string) {
context.logger.warn(str);
context.logger.error(str);
},
getErrHelpWidth(): number {
return 0;
Expand Down
21 changes: 14 additions & 7 deletions src/handlers/query-wallet.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ethers } from "ethers";
import { Context } from "../types";
import { RPCHandler } from "@ubiquity-dao/rpc-handler";
import { addCommentToIssue } from "../utils";

function extractEnsName(text: string) {
const ensRegex = /^(?=.{3,40}$)([a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/gm;
Expand All @@ -21,33 +22,39 @@ export async function registerWallet(context: Context, body: string) {
const ensName = extractEnsName(body.replace("/wallet", "").trim());

if (!address && ensName) {
context.logger.debug("Trying to resolve address from ENS name", { ensName });
logger.debug("Trying to resolve address from ENS name", { ensName });
address = await resolveAddress(ensName);
if (!address) {
throw new Error(`Resolving address from ENS name failed: ${ensName}`);
}
context.logger.debug("Resolved address from ENS name", { ensName, address });
logger.debug("Resolved address from ENS name", { ensName, address });
}

if (!address) {
return context.logger.info("Skipping to register a wallet address because both address/ens doesn't exist");
await addCommentToIssue(context, logger.info("Skipping to register a wallet address because both address/ens doesn't exist").logMessage.diff);
return;
}

if (config.registerWalletWithVerification) {
registerWalletWithVerification(context, body, address);
}

if (address == ethers.ZeroAddress) {
return logger.error("Skipping to register a wallet address because user is trying to set their address to null address");
await addCommentToIssue(
context,
logger.error("Skipping to register a wallet address because user is trying to set their address to null address").logMessage.diff
);

return;
}

// Makes sure that the address is check-summed
address = ethers.getAddress(address);

if (payload.comment) {
const { wallet } = adapters.supabase;
await wallet.upsertWalletAddress(context, address);
return context.logger.ok("Successfully registered wallet address", { sender, address });

await addCommentToIssue(context, logger.ok("Successfully registered wallet address", { sender, address }).logMessage.diff);
} else {
throw new Error("Payload comment is undefined");
}
Expand All @@ -67,7 +74,7 @@ function registerWalletWithVerification(context: Context, body: string, address:
throw new Error(failedSigLogMsg);
}
} catch (e) {
context.logger.fatal("Exception thrown by verifyMessage for /wallet: ", e, failedSigLogMsg);
context.logger.fatal("Exception thrown by verifyMessage for /wallet: ", { e, failedSigLogMsg });
throw new Error(failedSigLogMsg);
}
}
Expand Down
68 changes: 11 additions & 57 deletions src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { Octokit } from "@octokit/rest";
import { createClient } from "@supabase/supabase-js";
import { Logs } from "@ubiquity-os/ubiquity-os-logger";
import { CommanderError } from "commander";
import { createAdapters } from "./adapters";
import { CommandParser } from "./handlers/command-parser";
import { Env, PluginInputs } from "./types";
import { Context } from "./types";
import { addCommentToIssue } from "./utils";

/**
* How a worker executes the plugin.
Expand All @@ -19,56 +21,7 @@ export async function plugin(inputs: PluginInputs, env: Env) {
config: inputs.settings,
octokit,
env,
logger: {
debug(message: unknown, ...optionalParams: unknown[]) {
console.debug(message, ...optionalParams);
},
async ok(message: unknown, ...optionalParams: unknown[]) {
console.log(message, ...optionalParams);
try {
await octokit.issues.createComment({
owner: context.payload.repository.owner.login,
issue_number: context.payload.issue.number,
repo: context.payload.repository.name,
body: `\`\`\`diff\n+ ${message}`,
});
} catch (e) {
console.error("Failed to post ok comment", e);
}
},
async info(message: unknown, ...optionalParams: unknown[]) {
console.log(message, ...optionalParams);
try {
await octokit.issues.createComment({
owner: context.payload.repository.owner.login,
issue_number: context.payload.issue.number,
repo: context.payload.repository.name,
body: `\`\`\`diff\n# ${message}`,
});
} catch (e) {
console.error("Failed to post info comment", e);
}
},
warn(message: unknown, ...optionalParams: unknown[]) {
console.warn(message, ...optionalParams);
},
async error(message: unknown, ...optionalParams: unknown[]) {
console.error(message, ...optionalParams);
try {
await octokit.issues.createComment({
owner: context.payload.repository.owner.login,
issue_number: context.payload.issue.number,
repo: context.payload.repository.name,
body: `\`\`\`diff\n- ${message} ${optionalParams}`,
});
} catch (e) {
console.error("Failed to post error comment", e);
}
},
fatal(message: unknown, ...optionalParams: unknown[]) {
console.error(message, ...optionalParams);
},
},
logger: new Logs("info"),
adapters: {} as ReturnType<typeof createAdapters>,
};

Expand All @@ -79,17 +32,18 @@ export async function plugin(inputs: PluginInputs, env: Env) {
try {
const args = inputs.eventPayload.comment.body.trim().split(/\s+/);
await commandParser.parse(args);
} catch (e) {
if (e instanceof CommanderError) {
if (e.code !== "commander.unknownCommand") {
await context.logger.error(e.message);
} catch (err) {
if (err instanceof CommanderError) {
if (err.code !== "commander.unknownCommand") {
await addCommentToIssue(context, `\`\`\`diff\n- ${err.message}`);
context.logger.error(err.message);
}
} else {
await context.logger.error(e);
throw e;
context.logger.error("An error occurred", { err });
throw err;
}
}
} else {
context.logger.warn(`Unsupported event: ${context.eventName}`);
context.logger.error(`Unsupported event: ${context.eventName}`);
}
}
10 changes: 2 additions & 8 deletions src/types/context.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Octokit } from "@octokit/rest";
import { EmitterWebhookEvent as WebhookEvent, EmitterWebhookEventName as WebhookEventName } from "@octokit/webhooks";
import { Logs } from "@ubiquity-os/ubiquity-os-logger";
import { createAdapters } from "../adapters";
import { Env } from "./env";
import { PluginSettings } from "./plugin-inputs";
Expand All @@ -17,12 +18,5 @@ export interface Context<T extends SupportedEventsU = SupportedEventsU, TU exten
adapters: ReturnType<typeof createAdapters>;
config: PluginSettings;
env: Env;
logger: {
fatal: (message: unknown, ...optionalParams: unknown[]) => void;
error: (message: unknown, ...optionalParams: unknown[]) => Promise<void>;
warn: (message: unknown, ...optionalParams: unknown[]) => void;
info: (message: unknown, ...optionalParams: unknown[]) => Promise<void>;
ok: (message: unknown, ...optionalParams: unknown[]) => Promise<void>;
debug: (message: unknown, ...optionalParams: unknown[]) => void;
};
logger: Logs;
}
20 changes: 20 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Context } from "./types";

export async function addCommentToIssue(context: Context, message: string | null) {
if (!message) {
context.logger.error("Message is not defined");
return;
}

const { payload } = context;
try {
await context.octokit.rest.issues.createComment({
owner: payload.repository.owner.login,
issue_number: payload.issue.number,
repo: payload.repository.name,
body: message,
});
} catch (err: unknown) {
throw new Error(context.logger.error("Failed to post comment", { error: err as Error }).logMessage.raw);
}
}
14 changes: 9 additions & 5 deletions tests/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { db } from "./__mocks__/db";
import { server } from "./__mocks__/node";
import commentCreatedPayload from "./__mocks__/payloads/comment-created.json";
import dbSeed from "./__mocks__/db-seed.json";
import { Logs } from "@ubiquity-os/ubiquity-os-logger";

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
Expand All @@ -31,7 +32,7 @@ describe("Wallet command tests", () => {
});

it("Should link a wallet", async () => {
const spy = jest.spyOn(console, "log");
const spy = jest.spyOn(Logs.prototype, "ok");
await plugin(
{
eventName: "issue_comment.created",
Expand All @@ -50,9 +51,12 @@ describe("Wallet command tests", () => {
{ SUPABASE_URL: process.env.SUPABASE_URL, SUPABASE_KEY: process.env.SUPABASE_KEY }
);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenLastCalledWith("Successfully registered wallet address", {
address: "0xefC0e701A824943b469a694aC564Aa1efF7Ab7dd",
sender: "ubiquibot",
});
expect(spy).toHaveBeenLastCalledWith(
"Successfully registered wallet address",
expect.objectContaining({
address: "0xefC0e701A824943b469a694aC564Aa1efF7Ab7dd",
sender: "ubiquibot",
})
);
}, 10000);
});
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2407,6 +2407,11 @@
axios "^1.7.1"
node-fetch "^3.3.2"

"@ubiquity-os/ubiquity-os-logger@^1.3.2":
version "1.3.2"
resolved "https://registry.yarnpkg.com/@ubiquity-os/ubiquity-os-logger/-/ubiquity-os-logger-1.3.2.tgz#4423bc0baeac5c2f73123d15fd961310521163cd"
integrity sha512-oTIzR8z4jAQmaeJp98t1bZUKE3Ws9pas0sbxt58fC37MwXclPMWrLO+a0JlhPkdJYsvpv/q/79wC2MKVhOIVXQ==

JSONStream@^1.3.5:
version "1.3.5"
resolved "https://registry.yarnpkg.com/JSONStream/-/JSONStream-1.3.5.tgz#3208c1f08d3a4d99261ab64f92302bc15e111ca0"
Expand Down