Skip to content

Commit

Permalink
fix(comments): make class logger private, remove comments
Browse files Browse the repository at this point in the history
  • Loading branch information
atticusofsparta committed Feb 14, 2024
1 parent 4ea04a7 commit 7483246
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 78 deletions.
13 changes: 7 additions & 6 deletions src/common/ArIO.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,13 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { ContractStateProvider, HTTPServiceInterface } from '../types.js';
import { AxiosHTTPService } from './http.js';
import { ArweaveTransactionID } from '../types.js';
import { ContractStateProvider } from '../types.js';
import { DefaultLogger } from './logger.js';

export class ArIO implements ContractStateProvider {
private contractStateProvider: ContractStateProvider;
http: HTTPServiceInterface;
logger: DefaultLogger;
private logger: DefaultLogger;

constructor({
contractStateProvider,
Expand All @@ -35,7 +34,9 @@ export class ArIO implements ContractStateProvider {
}) {
this.contractStateProvider = contractStateProvider;
this.logger = logger;
this.http = new AxiosHTTPService({ url: '', logger }); // empty url allows for full url to be passed in get and post requests instead of the endpoint
this.logger.debug(
`ArIO initialized with ${contractStateProvider.constructor.name} as contract state provider`,
);
}

/**
Expand All @@ -45,7 +46,7 @@ export class ArIO implements ContractStateProvider {
async getContractState<ContractState>({
contractTxId,
}: {
contractTxId: string;
contractTxId: ArweaveTransactionID;
}): Promise<ContractState> {
return this.contractStateProvider.getContractState({ contractTxId });
}
Expand Down
48 changes: 15 additions & 33 deletions src/common/ContractStateProviders/ArNSRemoteCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,64 +14,46 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { ContractStateProvider, HTTPServiceInterface } from '../../types.js';
import { validateArweaveId } from '../../utils/index.js';
import { BadRequest } from '../error.js';
import {
ArweaveTransactionID,
ContractStateProvider,
HTTPClient,
} from '../../types.js';
import { AxiosHTTPService } from '../http.js';
import { DefaultLogger } from '../logger.js';

export class ArNSRemoteCache implements ContractStateProvider {
protected logger: DefaultLogger;
http: HTTPServiceInterface;
private logger: DefaultLogger;
private http: HTTPClient;
private apiVersion = 'v1' as const; // use v1 endpoints
constructor({
url = 'api.arns.app',
protocol = 'https',
url = 'https://api.arns.app',
logger = new DefaultLogger({
level: 'debug',
logFormat: 'simple',
}),
version = 'v1',
}: {
protocol?: 'http' | 'https' | 'ws';
url?: string;
logger?: DefaultLogger;
version?: string;
}) {
this.logger = logger;
this.http = new AxiosHTTPService({
url: `${protocol}://${url}/${version}`,
url: `${url}/${this.apiVersion}`,
logger,
});
}

async getContractState<ContractState>({
contractTxId,
}: {
contractTxId: string;
contractTxId: ArweaveTransactionID;
}): Promise<ContractState> {
if (!validateArweaveId(contractTxId)) {
throw new BadRequest(`Invalid contract id: ${contractTxId}`);
}
this.logger.debug(`Fetching contract state`);

const response = await this.http
.get<ContractState>({ endpoint: `/contract/${contractTxId}` })
.catch((error) => {
this.logger.debug(`Failed to fetch contract state: ${error}`);
return error;
});

if (!response) {
throw new BadRequest(
`Failed to fetch contract state. ${response?.status} ${response?.statusText()}`,
);
}
const result = await response.json();

this.logger.debug(
`Fetched contract state. Size: ${response?.headers?.get('content-length')} bytes.`,
);
const state = await this.http.get<ContractState>({
endpoint: `/contract/${contractTxId.toString()}`,
});

return result;
return state;
}
}
13 changes: 5 additions & 8 deletions src/common/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,21 @@ import { AxiosInstance } from 'axios';
import { Readable } from 'stream';
import { ReadableStream } from 'stream/web';

import { HTTPServiceInterface, Logger } from '../types.js';
import { HTTPClient, Logger } from '../types.js';
import { createAxiosInstance } from '../utils/httpClient.js';
import { FailedRequestError } from './error.js';

export class AxiosHTTPService implements HTTPServiceInterface {
protected axios: AxiosInstance;
protected logger: Logger;
export class AxiosHTTPService implements HTTPClient {
private axios: AxiosInstance;
private logger: Logger;

// TODO: re-implement axios-retry. Currently that package is broken for nodenext.
constructor({
url,
// retryConfig,
logger,
}: {
url: string;
// retryConfig?: IAxiosRetryConfig;

logger: Logger;
}) {
this.logger = logger;
Expand All @@ -52,8 +51,6 @@ export class AxiosHTTPService implements HTTPServiceInterface {
}
},
},
// retryConfig,
// logger: this.logger,
});
}
async get<T>({
Expand Down
2 changes: 1 addition & 1 deletion src/common/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { Logger } from '../types.js';
import { version } from '../version.js';

export class DefaultLogger implements Logger {
logger: winston.Logger;
private logger: winston.Logger;
constructor({
level = 'info',
logFormat = 'simple',
Expand Down
40 changes: 38 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,17 @@
import { Readable } from 'stream';
import { ReadableStream } from 'stream/web';

import { ARWEAVE_TX_REGEX } from './constants.js';

export interface ContractStateProvider {
/**
* The ContractStateProvider interface is used to define a contract state provider.
*/
getContractState<T>({ contractTxId }: { contractTxId: string }): Promise<T>;
getContractState<T>({
contractTxId,
}: {
contractTxId: ArweaveTransactionID;
}): Promise<T>;
}
/* eslint-disable @typescript-eslint/no-explicit-any */
export interface Logger {
Expand All @@ -34,7 +40,7 @@ export interface Logger {
}
/* eslint-enable @typescript-eslint/no-explicit-any */

export interface HTTPServiceInterface {
export interface HTTPClient {
get<T>({
endpoint,
signal,
Expand All @@ -60,3 +66,33 @@ export interface HTTPServiceInterface {
data: Readable | ReadableStream | Buffer;
}): Promise<T>;
}

export interface Equatable<T> {
equals(other: T): boolean;
}

export class ArweaveTransactionID implements Equatable<ArweaveTransactionID> {
constructor(private readonly transactionId?: string) {
if (transactionId === undefined || !ARWEAVE_TX_REGEX.test(transactionId)) {
throw new Error(
'Transaction ID should be a 43-character, alphanumeric string potentially including "-" and "_" characters.',
);
}
}

[Symbol.toPrimitive](hint?: string): string {
if (hint === 'number') {
throw new Error('Transaction IDs cannot be interpreted as a number!');
}

return this.toString();
}

toString(): string {
return this.transactionId ?? '';
}

equals(entityId: ArweaveTransactionID): boolean {
return this.transactionId === entityId.transactionId;
}
}
25 changes: 0 additions & 25 deletions src/utils/httpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,34 +16,13 @@
*/
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';

// import { DefaultLogger } from '../common/logger.js';
// import { Logger } from '../types.js';

// import { version } from '../version.js';

// TODO: re-implement axios-retry. Currently latest version of axios-retry is broken for node-next builds on v4.0.0
export interface AxiosInstanceParameters {
axiosConfig?: Omit<AxiosRequestConfig, 'validateStatus'>;
// retryConfig?: Record<string, string>;
// logger?: Logger;
}

export const createAxiosInstance = ({
//logger = new DefaultLogger(),
axiosConfig = {},
// retryConfig = {
// retryDelay: axiosRetry.exponentialDelay,
// retries: 3,
// retryCondition: (error) => {
// return (
// !(error instanceof CanceledError) &&
// axiosRetry.isNetworkOrIdempotentRequestError(error)
// );
// },
// onRetry: (retryCount, error) => {
// logger.debug(`Request failed, ${error}. Retry attempt #${retryCount}...`);
// },
// },
}: AxiosInstanceParameters = {}): AxiosInstance => {
const axiosInstance = axios.create({
...axiosConfig,
Expand All @@ -53,9 +32,5 @@ export const createAxiosInstance = ({
validateStatus: () => true, // don't throw on non-200 status codes
});

// eslint-disable-next-line
// if (retryConfig.retries && retryConfig.retries > 0) {
// axiosRetry(axiosInstance, retryConfig);
// }
return axiosInstance;
};
6 changes: 3 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "es2021",
"target": "esnext",
"allowSyntheticDefaultImports": true,
"lib": ["esnext", "dom"],
"outDir": "./lib/esm",
Expand All @@ -22,6 +22,6 @@
"skipLibCheck": true,
"strictNullChecks": true
},
"include": ["src"],
"exclude": ["lib", "node_modules"]
"include": ["src", "resources"],
"exclude": ["lib", "node_modules", "bundles"]
}

0 comments on commit 7483246

Please sign in to comment.