Skip to content

Commit

Permalink
Merge pull request #722 from golemfactory/feature/JST-651/disallow-an…
Browse files Browse the repository at this point in the history
…y-in-sdk-source

JST-651/disallow any in sdk source
  • Loading branch information
SewerynKras authored Dec 15, 2023
2 parents 6731207 + 813c49d commit 5032fd1
Show file tree
Hide file tree
Showing 31 changed files with 97 additions and 64 deletions.
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
"@types/jest": "^29.5.10",
"@types/node": "^20.10.0",
"@types/supertest": "^2.0.16",
"@types/tmp": "^0.2.6",
"@types/uuid": "^9.0.7",
"@typescript-eslint/eslint-plugin": "^6.13.1",
"@typescript-eslint/parser": "^6.13.1",
Expand Down
8 changes: 7 additions & 1 deletion src/activity/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ export interface ActivityOptions {
eventTarget?: EventTarget;
}

type AxiosError = Error & { response: { status: number }; code: string };
function isAxiosError(error: Error | AxiosError): error is AxiosError {
return Boolean(error && "response" in error && typeof error.response === "object" && "status" in error.response);
}

/**
* Activity module - an object representing the runtime environment on the provider in accordance with the `Package` specification.
* As part of a given activity, it is possible to execute exe script commands and capture their results.
Expand Down Expand Up @@ -338,7 +343,8 @@ export class Activity {
throw new GolemError(`Command #${cmdIndex || 0} getExecBatchResults error: ${error.message}`);
}

private isTimeoutError(error) {
private isTimeoutError(error: Error | AxiosError) {
if (!isAxiosError(error)) return false;
const timeoutMsg = error.message && error.message.includes("timeout");
return (
(error.response && error.response.status === 408) ||
Expand Down
5 changes: 3 additions & 2 deletions src/agreement/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { AgreementConfig } from "./config";
import { Events } from "../events";
import { YagnaApi } from "../utils/yagna/yagna";
import { GolemError } from "../error/golem-error";
import { ProposalProperties } from "../market/proposal";

/**
* AgreementFactory
Expand Down Expand Up @@ -43,8 +44,8 @@ export class AgreementFactory {
});
const { data } = await this.yagnaApi.market.getAgreement(agreementId);
const provider = {
name: data?.offer.properties["golem.node.id.name"],
id: data?.offer.providerId,
name: (data.offer.properties as ProposalProperties)["golem.node.id.name"],
id: data.offer.providerId,
};
if (!provider.id || !provider.name) throw new GolemError("Unable to get provider info");
const agreement = new Agreement(agreementId, provider, this.yagnaApi, this.options);
Expand Down
6 changes: 3 additions & 3 deletions src/agreement/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,14 @@ export class AgreementPoolService {
* @return Agreement
*/
async getAgreement(): Promise<Agreement> {
let agreement;
let agreement: Agreement | undefined;
while (!agreement && this.isServiceRunning) {
agreement = await this.getAgreementFormPool();
if (!agreement) {
await sleep(2);
}
}
if (!agreement && !this.isServiceRunning) {
if (!agreement || !this.isServiceRunning) {
throw new GolemError("Unable to get agreement. Agreement service is not running");
}
return agreement;
Expand Down Expand Up @@ -172,7 +172,7 @@ export class AgreementPoolService {
);
}

async createAgreement(candidate) {
async createAgreement(candidate: AgreementCandidate) {
try {
let agreement = await Agreement.create(candidate.proposal.id, this.yagnaApi, this.config.options);
agreement = await this.waitForAgreementApproval(agreement);
Expand Down
16 changes: 12 additions & 4 deletions src/events/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class CustomEvent<DataType> extends Event {
readonly detail: DataType;
readonly name: string;
readonly timestamp: number;
constructor(type, data) {
constructor(type: string, data: { detail: DataType } & EventInit) {
super(type, data);
this.detail = data.detail;
this.name = this.constructor.name;
Expand All @@ -25,13 +25,21 @@ class CustomEvent<DataType> extends Event {
}

export abstract class BaseEvent<DataType> extends CustomEvent<DataType> {
constructor(data?: DataType) {
constructor(data: DataType) {
super(EVENT_TYPE, { detail: data });
}
}

export class ComputationStarted extends BaseEvent<undefined> {}
export class ComputationFinished extends BaseEvent<undefined> {}
export class ComputationStarted extends BaseEvent<undefined> {
constructor() {
super(undefined);
}
}
export class ComputationFinished extends BaseEvent<undefined> {
constructor() {
super(undefined);
}
}
export class ComputationFailed extends BaseEvent<{ reason?: string }> {}
export class TaskStarted extends BaseEvent<{
id: string;
Expand Down
2 changes: 2 additions & 0 deletions src/executor/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ export class ExecutorConfig {
YAGNA_SUBNET: null,
},
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore FIXME: this weirdness may not be needed anymore?
Object.keys(options).forEach((key) => (this[key] = options[key]));
this.activityExecuteTimeout = options.activityExecuteTimeout || options.taskTimeout;
const apiKey = options?.yagnaOptions?.apiKey || processEnv.env.YAGNA_APPKEY;
Expand Down
8 changes: 4 additions & 4 deletions src/market/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,19 +60,19 @@ export class DecorationsBuilder {
if (!decorations.constraints.length) constraints = "(&)";
else if (decorations.constraints.length == 1) constraints = decorations.constraints[0];
else constraints = `(&${decorations.constraints.join("\n\t")})`;
const properties = {};
const properties: Record<string, string | number | boolean> = {};
decorations.properties.forEach((prop) => (properties[prop.key] = prop.value));
return { constraints, properties };
}
private parseConstraint(constraint): Constraint {
private parseConstraint(constraint: string): Constraint {
for (const key in ComparisonOperator) {
const value = ComparisonOperator[key];
const value = ComparisonOperator[key as keyof typeof ComparisonOperator];
const parsedConstraint = constraint.slice(1, -1).split(value);
if (parsedConstraint.length === 2) {
return {
key: parsedConstraint[0],
value: parsedConstraint[1],
comparisonOperator: ComparisonOperator[key],
comparisonOperator: value,
};
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/market/demand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ export class Demand extends EventTarget {
* @hidden
*/
export class DemandEvent extends Event {
readonly proposal: Proposal;
readonly proposal?: Proposal;
readonly error?: Error;

/**
Expand All @@ -253,7 +253,7 @@ export class DemandEvent extends Event {
* @param data object with proposal data:
* @param error optional error if occurred while subscription is active
*/
constructor(type, data?, error?) {
constructor(type: string, data?: (Proposal & EventInit) | undefined, error?: GolemError | undefined) {
super(type, data);
this.proposal = data;
this.error = error;
Expand Down
2 changes: 1 addition & 1 deletion src/market/proposal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ export class Proposal {
}

async respond(chosenPlatform: string) {
this.demandRequest.properties["golem.com.payment.chosen-platform"] = chosenPlatform;
(this.demandRequest.properties as ProposalProperties)["golem.com.payment.chosen-platform"] = chosenPlatform;
const { data: counteringProposalId } = await this.api
.counterProposalDemand(this.subscriptionId, this.id, this.demandRequest, { timeout: 20000 })
.catch((e) => {
Expand Down
6 changes: 4 additions & 2 deletions src/market/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export class MarketService {
private demandEventListener(event: Event) {
const proposal = (event as DemandEvent).proposal;
const error = (event as DemandEvent).error;
if (error) {
if (error || !proposal) {
this.logger?.error("Subscription failed. Trying to subscribe a new one...");
this.resubscribeDemand().catch((e) => this.logger?.warn(e));
return;
Expand All @@ -98,7 +98,9 @@ export class MarketService {
let attempt = 1;
let success = false;
while (!success && attempt <= this.maxResubscribeRetries) {
success = await this.createDemand().catch((e) => this.logger?.error(`Could not resubscribe demand. ${e}`));
success = Boolean(
await this.createDemand().catch((e) => this.logger?.error(`Could not resubscribe demand. ${e}`)),
);
++attempt;
await sleep(20);
}
Expand Down
2 changes: 1 addition & 1 deletion src/network/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { NetworkInfo } from "./network";
*/
export class NetworkNode {
constructor(
public readonly id,
public readonly id: string,
public readonly ip: IPv4,
private getNetworkInfo: () => NetworkInfo,
private apiUrl: string,
Expand Down
23 changes: 12 additions & 11 deletions src/payment/payments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,11 @@ export class Payments extends EventTarget {
for (const event of invoiceEvents) {
if (!this.isRunning) return;
if (event.eventType !== "InvoiceReceivedEvent") continue;
const invoice = await Invoice.create(event["invoiceId"], this.yagnaApi, { ...this.options }).catch(
(e) =>
this.logger?.error(
`Unable to create invoice ID: ${event["invoiceId"]}. ${e?.response?.data?.message || e}`,
),
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore FIXME: ya-ts-client does not provide invoiceId in the event even though it is in the API response
const invoiceId = event["invoiceId"];
const invoice = await Invoice.create(invoiceId, this.yagnaApi, { ...this.options }).catch(
(e) => this.logger?.error(`Unable to create invoice ID: ${invoiceId}. ${e?.response?.data?.message || e}`),
);
if (!invoice) continue;
this.dispatchEvent(new InvoiceEvent(PAYMENT_EVENT_TYPE, invoice));
Expand Down Expand Up @@ -98,11 +98,12 @@ export class Payments extends EventTarget {
for (const event of debitNotesEvents) {
if (!this.isRunning) return;
if (event.eventType !== "DebitNoteReceivedEvent") continue;
const debitNote = await DebitNote.create(event["debitNoteId"], this.yagnaApi, { ...this.options }).catch(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore FIXME: ya-ts-client does not provide debitNoteId in the event even though it is in the API response
const debitNoteId = event["debitNoteId"];
const debitNote = await DebitNote.create(debitNoteId, this.yagnaApi, { ...this.options }).catch(
(e) =>
this.logger?.error(
`Unable to create debit note ID: ${event["debitNoteId"]}. ${e?.response?.data?.message || e}`,
),
this.logger?.error(`Unable to create debit note ID: ${debitNoteId}. ${e?.response?.data?.message || e}`),
);
if (!debitNote) continue;
this.dispatchEvent(new DebitNoteEvent(PAYMENT_EVENT_TYPE, debitNote));
Expand Down Expand Up @@ -139,7 +140,7 @@ export class InvoiceEvent extends Event {
* @param type A string with the name of the event:
* @param data object with invoice data:
*/
constructor(type, data) {
constructor(type: string, data: EventInit & Invoice) {
super(type, data);
this.invoice = data;
}
Expand All @@ -156,7 +157,7 @@ export class DebitNoteEvent extends Event {
* @param type A string with the name of the event:
* @param data object with debit note data:
*/
constructor(type, data) {
constructor(type: string, data: EventInit & DebitNote) {
super(type, data);
this.debitNote = data;
}
Expand Down
2 changes: 1 addition & 1 deletion src/payment/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ export class PaymentService {
}
}

private async subscribePayments(event) {
private async subscribePayments(event: Event) {
if (event instanceof InvoiceEvent) this.processInvoice(event.invoice).then();
if (event instanceof DebitNoteEvent) this.processDebitNote(event.debitNote).then();
}
Expand Down
18 changes: 9 additions & 9 deletions src/script/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ const EMPTY_ERROR_RESULT = new Result({
* @hidden
*/
export class Command<T = unknown> {
protected args: object;
protected args: Record<string, unknown>;

constructor(
private commandName: string,
args?: object,
args?: Record<string, unknown>,
) {
this.args = args || {};
}
Expand Down Expand Up @@ -59,7 +59,7 @@ export class Command<T = unknown> {
* @hidden
*/
export class Deploy extends Command {
constructor(args?: object) {
constructor(args?: Record<string, unknown>) {
super("deploy", args);
}
}
Expand All @@ -68,7 +68,7 @@ export class Deploy extends Command {
* @hidden
*/
export class Start extends Command {
constructor(args?: object) {
constructor(args?: Record<string, unknown>) {
super("start", args);
}
}
Expand Down Expand Up @@ -103,7 +103,7 @@ export class Run extends Command {
}

export class Terminate extends Command {
constructor(args?: object) {
constructor(args?: Record<string, unknown>) {
super("terminate", args);
}
}
Expand Down Expand Up @@ -139,7 +139,7 @@ export class UploadFile extends Transfer {
}

async after(result: Result): Promise<Result> {
await this.storageProvider.release([this.args["from"]]);
await this.storageProvider.release([this.args["from"] as string]);
return result;
}
}
Expand All @@ -162,7 +162,7 @@ export class UploadData extends Transfer {
}

async after(result: Result): Promise<Result> {
await this.storageProvider.release([this.args["from"]]);
await this.storageProvider.release([this.args["from"] as string]);
return result;
}
}
Expand All @@ -185,7 +185,7 @@ export class DownloadFile extends Transfer {
}

async after(result: Result): Promise<Result> {
await this.storageProvider.release([this.args["to"]]);
await this.storageProvider.release([this.args["to"] as string]);
return result;
}
}
Expand All @@ -212,7 +212,7 @@ export class DownloadData extends Transfer<Uint8Array> {
}

async after(result: Result): Promise<Result<Uint8Array>> {
await this.storageProvider.release([this.args["to"]]);
await this.storageProvider.release([this.args["to"] as string]);
if (result.result === ResultState.Ok) {
return new Result<Uint8Array>({
...result,
Expand Down
2 changes: 1 addition & 1 deletion src/stats/abstract_aggregator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export abstract class AbstractAggregator<T, R extends ItemInfo> {
protected getByField(field: string, value: string | number): Collection<R> {
return this.getAll().where(field, "==", value);
}
protected updateItemInfo(id: string, data) {
protected updateItemInfo(id: string, data: Partial<R>) {
const item = this.items.get(id);
if (!item) return;
this.items?.set(id, {
Expand Down
2 changes: 1 addition & 1 deletion src/stats/activities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ interface Payload {
}

export class Activities extends AbstractAggregator<Payload, ActivityInfo> {
beforeAdd(payload): ActivityInfo {
beforeAdd(payload: ActivityInfo): ActivityInfo {
return payload;
}
getByTaskId(taskId: string) {
Expand Down
2 changes: 1 addition & 1 deletion src/stats/agreements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ interface Payload {
}

export class Agreements extends AbstractAggregator<Payload, AgreementInfo> {
beforeAdd(payload): AgreementInfo {
beforeAdd(payload: AgreementInfo): AgreementInfo {
return { ...payload, status: AgreementStatusEnum.Pending };
}
confirm(id: string) {
Expand Down
2 changes: 1 addition & 1 deletion src/stats/allocations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ interface Payload {
}

export class Allocations extends AbstractAggregator<Payload, AllocationInfo> {
beforeAdd(payload): AllocationInfo {
beforeAdd(payload: Payload): AllocationInfo {
return payload;
}
}
Loading

0 comments on commit 5032fd1

Please sign in to comment.