Convert comments to tsdoc in REST sample (#606)

Signed-off-by: James Taylor <jamest@uk.ibm.com>
This commit is contained in:
James Taylor 2022-02-01 16:12:07 +00:00 committed by GitHub
parent e2d351ed61
commit 5d3cc66c25
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 87 additions and 82 deletions

View file

@ -20,7 +20,7 @@ export const ORG2 = 'Org2';
export const JOB_QUEUE_NAME = 'submit'; export const JOB_QUEUE_NAME = 'submit';
/* /**
* Log level for the REST server * Log level for the REST server
*/ */
export const logLevel = env export const logLevel = env
@ -28,7 +28,7 @@ export const logLevel = env
.default('info') .default('info')
.asEnum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']); .asEnum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']);
/* /**
* The port to start the REST server on * The port to start the REST server on
*/ */
export const port = env export const port = env
@ -37,7 +37,7 @@ export const port = env
.example('3000') .example('3000')
.asPortNumber(); .asPortNumber();
/* /**
* The type of backoff to use for retrying failed submit jobs * The type of backoff to use for retrying failed submit jobs
*/ */
export const submitJobBackoffType = env export const submitJobBackoffType = env
@ -45,7 +45,7 @@ export const submitJobBackoffType = env
.default('fixed') .default('fixed')
.asEnum(['fixed', 'exponential']); .asEnum(['fixed', 'exponential']);
/* /**
* Backoff delay for retrying failed submit jobs in milliseconds * Backoff delay for retrying failed submit jobs in milliseconds
*/ */
export const submitJobBackoffDelay = env export const submitJobBackoffDelay = env
@ -54,7 +54,7 @@ export const submitJobBackoffDelay = env
.example('3000') .example('3000')
.asIntPositive(); .asIntPositive();
/* /**
* The total number of attempts to try a submit job until it completes * The total number of attempts to try a submit job until it completes
*/ */
export const submitJobAttempts = env export const submitJobAttempts = env
@ -63,7 +63,7 @@ export const submitJobAttempts = env
.example('5') .example('5')
.asIntPositive(); .asIntPositive();
/* /**
* The maximum number of submit jobs that can be processed in parallel * The maximum number of submit jobs that can be processed in parallel
*/ */
export const submitJobConcurrency = env export const submitJobConcurrency = env
@ -72,7 +72,7 @@ export const submitJobConcurrency = env
.example('5') .example('5')
.asIntPositive(); .asIntPositive();
/* /**
* The number of completed submit jobs to keep * The number of completed submit jobs to keep
*/ */
export const maxCompletedSubmitJobs = env export const maxCompletedSubmitJobs = env
@ -81,7 +81,7 @@ export const maxCompletedSubmitJobs = env
.example('1000') .example('1000')
.asIntPositive(); .asIntPositive();
/* /**
* The number of failed submit jobs to keep * The number of failed submit jobs to keep
*/ */
export const maxFailedSubmitJobs = env export const maxFailedSubmitJobs = env
@ -90,7 +90,7 @@ export const maxFailedSubmitJobs = env
.example('1000') .example('1000')
.asIntPositive(); .asIntPositive();
/* /**
* Whether to initialise a scheduler for the submit job queue * Whether to initialise a scheduler for the submit job queue
* There must be at least on queue scheduler to handle retries and you may want * There must be at least on queue scheduler to handle retries and you may want
* more than one for redundancy * more than one for redundancy
@ -101,7 +101,7 @@ export const submitJobQueueScheduler = env
.example('true') .example('true')
.asBoolStrict(); .asBoolStrict();
/* /**
* Whether to convert discovered host addresses to be 'localhost' * Whether to convert discovered host addresses to be 'localhost'
* This should be set to 'true' when running a docker composed fabric network on the * This should be set to 'true' when running a docker composed fabric network on the
* local system, e.g. using the test network; otherwise should it should be 'false' * local system, e.g. using the test network; otherwise should it should be 'false'
@ -112,7 +112,7 @@ export const asLocalhost = env
.example('true') .example('true')
.asBoolStrict(); .asBoolStrict();
/* /**
* The Org1 MSP ID * The Org1 MSP ID
*/ */
export const mspIdOrg1 = env export const mspIdOrg1 = env
@ -121,7 +121,7 @@ export const mspIdOrg1 = env
.example(`${ORG1}MSP`) .example(`${ORG1}MSP`)
.asString(); .asString();
/* /**
* The Org2 MSP ID * The Org2 MSP ID
*/ */
export const mspIdOrg2 = env export const mspIdOrg2 = env
@ -130,7 +130,7 @@ export const mspIdOrg2 = env
.example(`${ORG2}MSP`) .example(`${ORG2}MSP`)
.asString(); .asString();
/* /**
* Name of the channel which the basic asset sample chaincode has been installed on * Name of the channel which the basic asset sample chaincode has been installed on
*/ */
export const channelName = env export const channelName = env
@ -139,7 +139,7 @@ export const channelName = env
.example('mychannel') .example('mychannel')
.asString(); .asString();
/* /**
* Name used to install the basic asset sample * Name used to install the basic asset sample
*/ */
export const chaincodeName = env export const chaincodeName = env
@ -148,7 +148,7 @@ export const chaincodeName = env
.example('basic') .example('basic')
.asString(); .asString();
/* /**
* The transaction submit timeout in seconds for commit notification to complete * The transaction submit timeout in seconds for commit notification to complete
*/ */
export const commitTimeout = env export const commitTimeout = env
@ -157,7 +157,7 @@ export const commitTimeout = env
.example('300') .example('300')
.asIntPositive(); .asIntPositive();
/* /**
* The transaction submit timeout in seconds for the endorsement to complete * The transaction submit timeout in seconds for the endorsement to complete
*/ */
export const endorseTimeout = env export const endorseTimeout = env
@ -166,7 +166,7 @@ export const endorseTimeout = env
.example('30') .example('30')
.asIntPositive(); .asIntPositive();
/* /**
* The transaction query timeout in seconds * The transaction query timeout in seconds
*/ */
export const queryTimeout = env export const queryTimeout = env
@ -175,7 +175,7 @@ export const queryTimeout = env
.example('3') .example('3')
.asIntPositive(); .asIntPositive();
/* /**
* The Org1 connection profile JSON * The Org1 connection profile JSON
*/ */
export const connectionProfileOrg1 = env export const connectionProfileOrg1 = env
@ -186,7 +186,7 @@ export const connectionProfileOrg1 = env
) )
.asJsonObject() as Record<string, unknown>; .asJsonObject() as Record<string, unknown>;
/* /**
* Certificate for an Org1 identity to evaluate and submit transactions * Certificate for an Org1 identity to evaluate and submit transactions
*/ */
export const certificateOrg1 = env export const certificateOrg1 = env
@ -195,7 +195,7 @@ export const certificateOrg1 = env
.example('"-----BEGIN CERTIFICATE-----\\n...\\n-----END CERTIFICATE-----\\n"') .example('"-----BEGIN CERTIFICATE-----\\n...\\n-----END CERTIFICATE-----\\n"')
.asString(); .asString();
/* /**
* Private key for an Org1 identity to evaluate and submit transactions * Private key for an Org1 identity to evaluate and submit transactions
*/ */
export const privateKeyOrg1 = env export const privateKeyOrg1 = env
@ -204,7 +204,7 @@ export const privateKeyOrg1 = env
.example('"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----\\n"') .example('"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----\\n"')
.asString(); .asString();
/* /**
* The Org2 connection profile JSON * The Org2 connection profile JSON
*/ */
export const connectionProfileOrg2 = env export const connectionProfileOrg2 = env
@ -215,7 +215,7 @@ export const connectionProfileOrg2 = env
) )
.asJsonObject() as Record<string, unknown>; .asJsonObject() as Record<string, unknown>;
/* /**
* Certificate for an Org2 identity to evaluate and submit transactions * Certificate for an Org2 identity to evaluate and submit transactions
*/ */
export const certificateOrg2 = env export const certificateOrg2 = env
@ -224,7 +224,7 @@ export const certificateOrg2 = env
.example('"-----BEGIN CERTIFICATE-----\\n...\\n-----END CERTIFICATE-----\\n"') .example('"-----BEGIN CERTIFICATE-----\\n...\\n-----END CERTIFICATE-----\\n"')
.asString(); .asString();
/* /**
* Private key for an Org2 identity to evaluate and submit transactions * Private key for an Org2 identity to evaluate and submit transactions
*/ */
export const privateKeyOrg2 = env export const privateKeyOrg2 = env
@ -233,7 +233,7 @@ export const privateKeyOrg2 = env
.example('"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----\\n"') .example('"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----\\n"')
.asString(); .asString();
/* /**
* The host the Redis server is running on * The host the Redis server is running on
*/ */
export const redisHost = env export const redisHost = env
@ -242,7 +242,7 @@ export const redisHost = env
.example('localhost') .example('localhost')
.asString(); .asString();
/* /**
* The port the Redis server is running on * The port the Redis server is running on
*/ */
export const redisPort = env export const redisPort = env
@ -251,7 +251,7 @@ export const redisPort = env
.example('6379') .example('6379')
.asPortNumber(); .asPortNumber();
/* /**
* Username for the Redis server * Username for the Redis server
*/ */
export const redisUsername = env export const redisUsername = env
@ -259,12 +259,12 @@ export const redisUsername = env
.example('fabric') .example('fabric')
.asString(); .asString();
/* /**
* Password for the Redis server * Password for the Redis server
*/ */
export const redisPassword = env.get('REDIS_PASSWORD').asString(); export const redisPassword = env.get('REDIS_PASSWORD').asString();
/* /**
* API key for Org1 * API key for Org1
* Specify this API key with the X-Api-Key header to use the Org1 connection profile and credentials * Specify this API key with the X-Api-Key header to use the Org1 connection profile and credentials
*/ */
@ -274,7 +274,7 @@ export const org1ApiKey = env
.example('123') .example('123')
.asString(); .asString();
/* /**
* API key for Org2 * API key for Org2
* Specify this API key with the X-Api-Key header to use the Org2 connection profile and credentials * Specify this API key with the X-Api-Key header to use the Org2 connection profile and credentials
*/ */

View file

@ -8,7 +8,7 @@
import { TimeoutError, TransactionError } from 'fabric-network'; import { TimeoutError, TransactionError } from 'fabric-network';
import { logger } from './logger'; import { logger } from './logger';
/* /**
* Base type for errors from the smart contract. * Base type for errors from the smart contract.
* *
* These errors will not be retried. * These errors will not be retried.
@ -25,7 +25,7 @@ export class ContractError extends Error {
} }
} }
/* /**
* Represents the error which occurs when the transaction being submitted or * Represents the error which occurs when the transaction being submitted or
* evaluated is not implemented in a smart contract. * evaluated is not implemented in a smart contract.
*/ */
@ -38,7 +38,7 @@ export class TransactionNotFoundError extends ContractError {
} }
} }
/* /**
* Represents the error which occurs in the basic asset transfer smart contract * Represents the error which occurs in the basic asset transfer smart contract
* implementation when an asset already exists. * implementation when an asset already exists.
*/ */
@ -51,7 +51,7 @@ export class AssetExistsError extends ContractError {
} }
} }
/* /**
* Represents the error which occurs in the basic asset transfer smart contract * Represents the error which occurs in the basic asset transfer smart contract
* implementation when an asset does not exist. * implementation when an asset does not exist.
*/ */
@ -64,26 +64,30 @@ export class AssetNotFoundError extends ContractError {
} }
} }
/* /**
* Enumeration of possible retry actions. * Enumeration of possible retry actions.
*
* WithExistingTransactionId - transactions should be retried using the same
* transaction ID to protect against duplicate transactions being committed if
* a timeout error occurs
*
* WithNewTransactionId - transactions which could not be committed due to
* other errors require a new transaction ID when retrying
*
* None - transactions that failed due to a duplicate transaction error, or
* errors from the smart contract, should not be retried
*/ */
export enum RetryAction { export enum RetryAction {
/**
* Transactions should be retried using the same transaction ID to protect
* against duplicate transactions being committed if a timeout error occurs
*/
WithExistingTransactionId, WithExistingTransactionId,
/**
* Transactions which could not be committed due to other errors require a
* new transaction ID when retrying
*/
WithNewTransactionId, WithNewTransactionId,
/**
* Transactions that failed due to a duplicate transaction error, or errors
* from the smart contract, should not be retried
*/
None, None,
} }
/* /**
* Get the required transaction retry action for an error. * Get the required transaction retry action for an error.
* *
* For this sample transactions are considered retriable if they fail with any * For this sample transactions are considered retriable if they fail with any
@ -92,11 +96,11 @@ export enum RetryAction {
* *
* You might decide to retry transactions which fail with specific errors * You might decide to retry transactions which fail with specific errors
* instead, for example: * instead, for example:
* MVCC_READ_CONFLICT * - MVCC_READ_CONFLICT
* PHANTOM_READ_CONFLICT * - PHANTOM_READ_CONFLICT
* ENDORSEMENT_POLICY_FAILURE * - ENDORSEMENT_POLICY_FAILURE
* CHAINCODE_VERSION_CONFLICT * - CHAINCODE_VERSION_CONFLICT
* EXPIRED_CHAINCODE * - EXPIRED_CHAINCODE
*/ */
export const getRetryAction = (err: unknown): RetryAction => { export const getRetryAction = (err: unknown): RetryAction => {
if (isDuplicateTransactionError(err) || err instanceof ContractError) { if (isDuplicateTransactionError(err) || err instanceof ContractError) {
@ -108,7 +112,7 @@ export const getRetryAction = (err: unknown): RetryAction => {
return RetryAction.WithNewTransactionId; return RetryAction.WithNewTransactionId;
}; };
/* /**
* Type guard to make catching unknown errors easier * Type guard to make catching unknown errors easier
*/ */
export const isErrorLike = (err: unknown): err is Error => { export const isErrorLike = (err: unknown): err is Error => {
@ -122,7 +126,7 @@ export const isErrorLike = (err: unknown): err is Error => {
); );
}; };
/* /**
* Checks whether an error was caused by a duplicate transaction. * Checks whether an error was caused by a duplicate transaction.
* *
* This is ...painful. * This is ...painful.
@ -155,13 +159,13 @@ export const isDuplicateTransactionError = (err: unknown): boolean => {
return isDuplicate === true; return isDuplicate === true;
}; };
/* /**
* Matches asset already exists error strings from the asset contract * Matches asset already exists error strings from the asset contract
* *
* The regex needs to match the following error messages: * The regex needs to match the following error messages:
* "the asset %s already exists" * - "the asset %s already exists"
* "The asset ${id} already exists" * - "The asset ${id} already exists"
* "Asset %s already exists" * - "Asset %s already exists"
*/ */
const matchAssetAlreadyExistsMessage = (message: string): string | null => { const matchAssetAlreadyExistsMessage = (message: string): string | null => {
const assetAlreadyExistsRegex = /([tT]he )?[aA]sset \w* already exists/g; const assetAlreadyExistsRegex = /([tT]he )?[aA]sset \w* already exists/g;
@ -178,13 +182,13 @@ const matchAssetAlreadyExistsMessage = (message: string): string | null => {
return null; return null;
}; };
/* /**
* Matches asset does not exist error strings from the asset contract * Matches asset does not exist error strings from the asset contract
* *
* The regex needs to match the following error messages: * The regex needs to match the following error messages:
* "the asset %s does not exist" * - "the asset %s does not exist"
* "The asset ${id} does not exist" * - "The asset ${id} does not exist"
* "Asset %s does not exist" * - "Asset %s does not exist"
*/ */
const matchAssetDoesNotExistMessage = (message: string): string | null => { const matchAssetDoesNotExistMessage = (message: string): string | null => {
const assetDoesNotExistRegex = /([tT]he )?[aA]sset \w* does not exist/g; const assetDoesNotExistRegex = /([tT]he )?[aA]sset \w* does not exist/g;
@ -201,12 +205,12 @@ const matchAssetDoesNotExistMessage = (message: string): string | null => {
return null; return null;
}; };
/* /**
* Matches transaction does not exist error strings from the contract API * Matches transaction does not exist error strings from the contract API
* *
* The regex needs to match the following error messages: * The regex needs to match the following error messages:
* "Failed to get transaction with id %s, error Entry not found in index" * - "Failed to get transaction with id %s, error Entry not found in index"
* "Failed to get transaction with id %s, error no such transaction ID [%s] in index" * - "Failed to get transaction with id %s, error no such transaction ID [%s] in index"
*/ */
const matchTransactionDoesNotExistMessage = ( const matchTransactionDoesNotExistMessage = (
message: string message: string
@ -228,11 +232,12 @@ const matchTransactionDoesNotExistMessage = (
return null; return null;
}; };
/* /**
* Handles errors from evaluating and submitting transactions. * Handles errors from evaluating and submitting transactions.
* *
* Smart contract errors from the the basic asset transfer samples do not use * Smart contract errors from the basic asset transfer samples do not use
* error codes so matching strings is the only option, which is not ideal. * error codes so matching strings is the only option, which is not ideal.
*
* Note: the error message text is not the same for the Go, Java, and * Note: the error message text is not the same for the Go, Java, and
* Javascript implementations of the chaincode! * Javascript implementations of the chaincode!
*/ */

View file

@ -18,7 +18,7 @@ import { logger } from './logger';
import { handleError } from './errors'; import { handleError } from './errors';
import * as protos from 'fabric-protos'; import * as protos from 'fabric-protos';
/* /**
* Creates an in memory wallet to hold credentials for an Org1 and Org2 user * Creates an in memory wallet to hold credentials for an Org1 and Org2 user
* *
* In this sample there is a single user for each MSP ID to demonstrate how * In this sample there is a single user for each MSP ID to demonstrate how
@ -55,7 +55,7 @@ export const createWallet = async (): Promise<Wallet> => {
return wallet; return wallet;
}; };
/* /**
* Create a Gateway connection * Create a Gateway connection
* *
* Gateway instances can and should be reused rather than connecting to submit every transaction * Gateway instances can and should be reused rather than connecting to submit every transaction
@ -89,7 +89,7 @@ export const createGateway = async (
return gateway; return gateway;
}; };
/* /**
* Get the network which the asset transfer sample chaincode is running on * Get the network which the asset transfer sample chaincode is running on
* *
* In addion to getting the contract, the network will also be used to * In addion to getting the contract, the network will also be used to
@ -100,7 +100,7 @@ export const getNetwork = async (gateway: Gateway): Promise<Network> => {
return network; return network;
}; };
/* /**
* Get the asset transfer sample contract and the qscc system contract * Get the asset transfer sample contract and the qscc system contract
* *
* The system contract is used for the liveness REST endpoint * The system contract is used for the liveness REST endpoint
@ -113,7 +113,7 @@ export const getContracts = async (
return { assetContract, qsccContract }; return { assetContract, qsccContract };
}; };
/* /**
* Evaluate a transaction and handle any errors * Evaluate a transaction and handle any errors
*/ */
export const evatuateTransaction = async ( export const evatuateTransaction = async (
@ -137,7 +137,7 @@ export const evatuateTransaction = async (
} }
}; };
/* /**
* Submit a transaction and handle any errors * Submit a transaction and handle any errors
*/ */
export const submitTransaction = async ( export const submitTransaction = async (
@ -159,7 +159,7 @@ export const submitTransaction = async (
} }
}; };
/* /**
* Get the validation code of the specified transaction * Get the validation code of the specified transaction
*/ */
export const getTransactionValidationCode = async ( export const getTransactionValidationCode = async (
@ -181,7 +181,7 @@ export const getTransactionValidationCode = async (
return validationCode; return validationCode;
}; };
/* /**
* Get the current block height * Get the current block height
* *
* This example of using a system contract is used for the liveness REST * This example of using a system contract is used for the liveness REST

View file

@ -52,7 +52,7 @@ const connection: ConnectionOptions = {
password: config.redisPassword, password: config.redisPassword,
}; };
/* /**
* Set up the queue for submit jobs * Set up the queue for submit jobs
*/ */
export const initJobQueue = (): Queue => { export const initJobQueue = (): Queue => {
@ -72,7 +72,7 @@ export const initJobQueue = (): Queue => {
return submitQueue; return submitQueue;
}; };
/* /**
* Set up a worker to process submit jobs on the queue, using the * Set up a worker to process submit jobs on the queue, using the
* processSubmitTransactionJob function below * processSubmitTransactionJob function below
*/ */
@ -104,7 +104,7 @@ export const initJobQueueWorker = (app: Application): Worker => {
return worker; return worker;
}; };
/* /**
* Process a submit transaction request from the job queue * Process a submit transaction request from the job queue
* *
* The job will be retried if this function throws an error * The job will be retried if this function throws an error
@ -209,7 +209,7 @@ export const processSubmitTransactionJob = async (
} }
}; };
/* /**
* Set up a scheduler for the submit job queue * Set up a scheduler for the submit job queue
* *
* This manages stalled and delayed jobs and is required for retries with backoff * This manages stalled and delayed jobs and is required for retries with backoff
@ -226,7 +226,7 @@ export const initJobQueueScheduler = (): QueueScheduler => {
return queueScheduler; return queueScheduler;
}; };
/* /**
* Helper to add a new submit transaction job to the queue * Helper to add a new submit transaction job to the queue
*/ */
export const addSubmitTransactionJob = async ( export const addSubmitTransactionJob = async (
@ -250,7 +250,7 @@ export const addSubmitTransactionJob = async (
return job.id; return job.id;
}; };
/* /**
* Helper to update the data for an existing job * Helper to update the data for an existing job
*/ */
export const updateJobData = async ( export const updateJobData = async (
@ -274,7 +274,7 @@ export const updateJobData = async (
await job.update(newData); await job.update(newData);
}; };
/* /**
* Gets a job summary * Gets a job summary
* *
* This function is used for the jobs REST endpoint * This function is used for the jobs REST endpoint
@ -325,7 +325,7 @@ export const getJobSummary = async (
return jobSummary; return jobSummary;
}; };
/* /**
* Get the current job counts * Get the current job counts
* *
* This function is used for the liveness REST endpoint * This function is used for the liveness REST endpoint

View file

@ -9,7 +9,7 @@ import IORedis, { Redis, RedisOptions } from 'ioredis';
import * as config from './config'; import * as config from './config';
import { logger } from './logger'; import { logger } from './logger';
/* /**
* Check whether the maxmemory-policy config is set to noeviction * Check whether the maxmemory-policy config is set to noeviction
* *
* BullMQ requires this setting in redis * BullMQ requires this setting in redis