portal-dashboard/app/data/pinning.ts

104 lines
2.9 KiB
TypeScript
Raw Permalink Normal View History

2024-03-26 14:54:51 +00:00
import { PROTOCOL_S5, Sdk } from "@lumeweb/portal-sdk";
import { useSdk } from "~/components/lib/sdk-context.js";
import { S5Client } from "@lumeweb/s5-js";
import { S5Error } from "@lumeweb/s5-js/lib/client.js";
export interface PinningStatus {
2024-03-26 14:54:51 +00:00
id: string;
progress: number;
status: "processing" | "completed";
}
// biome-ignore lint/complexity/noStaticOnlyClass: <explanation>
2024-03-21 05:15:12 +00:00
export class PinningProcess {
2024-03-26 14:54:51 +00:00
private static instances: Map<string, PinningStatus> = new Map();
private static sdk?: Sdk;
static async pin(id: string): Promise<{ success: boolean; message: string }> {
try {
const s5 = PinningProcess.sdk?.protocols().get<S5Client>("s5")!.getSdk()!;
console.log({ s5 });
if (PinningProcess.instances.has(id)) {
return { success: false, message: "ID is already being processed" };
}
const pinningStatus: PinningStatus = {
id,
progress: 0,
status: "processing",
};
const response = await s5.pin(id);
console.log({ response });
PinningProcess.instances.set(id, pinningStatus);
return { success: true, message: "Pinning process started" };
} catch (e) {
console.error(e);
return { success: false, message: "Pinning process failed" };
}
2024-03-26 14:54:51 +00:00
}
2024-03-26 14:54:51 +00:00
static async unpin(
id: string,
): Promise<{ success: boolean; message: string }> {
if (!PinningProcess.instances.has(id)) {
return { success: false, message: "ID not found or not being processed" };
}
2024-03-26 14:54:51 +00:00
await PinningProcess.sdk
?.protocols()
.get<S5Client>(PROTOCOL_S5)!
.getSdk()
.unpin(id);
return { success: true, message: "Pinning process removed" };
}
static *pollAllProgress(): Generator<PinningStatus[], void, unknown> {
let allStatuses = Array.from(PinningProcess.instances.values());
let inProgress = allStatuses.some((status) => {
PinningProcess.checkStatus(status.id);
return status.status !== "processing";
2024-03-26 14:54:51 +00:00
});
while (inProgress) {
yield allStatuses;
allStatuses = Array.from(PinningProcess.instances.values());
inProgress = allStatuses.some((status) => {
PinningProcess.checkStatus(status.id);
return status.status !== "completed";
});
}
2024-03-26 14:54:51 +00:00
yield allStatuses ?? []; // Yield the final statuses
}
private static async checkStatus(id: string) {
const s5 = PinningProcess.sdk
?.protocols()
.get<S5Client>(PROTOCOL_S5)!
.getSdk()!;
try {
const ret = await s5.pinStatus(id);
const status = PinningProcess.instances.get(id);
if (!status) {
return;
}
status.progress = ret.progress;
status.status = ret.status as any;
} catch (e) {
if ((e as S5Error).statusCode == 404) {
PinningProcess.instances.delete(id);
}
return;
}
2024-03-26 14:54:51 +00:00
}
2024-03-26 14:54:51 +00:00
public static setupSdk(sdk: Sdk) {
PinningProcess.sdk = sdk;
}
}