Skip to content

Commit

Permalink
chore: run prettier (#1224)
Browse files Browse the repository at this point in the history
  • Loading branch information
stbrody authored Jun 7, 2024
1 parent c603f15 commit 7115d46
Show file tree
Hide file tree
Showing 13 changed files with 109 additions and 114 deletions.
5 changes: 4 additions & 1 deletion src/__tests__/ceramic_integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,10 @@ describe('Ceramic Integration Test', () => {
await cas1.stop()
await cas2.stop()
await Promise.all([dbConnection1.destroy(), dbConnection2.destroy()])
await Promise.all([replicaDbConnection1.connection.destroy(), replicaDbConnection2.connection.destroy()])
await Promise.all([
replicaDbConnection1.connection.destroy(),
replicaDbConnection2.connection.destroy(),
])
await Promise.all([ceramic1.close(), ceramic2.close()])
})

Expand Down
12 changes: 3 additions & 9 deletions src/ancillary/__tests__/anchor-request-params-parser.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { describe, expect, test } from '@jest/globals'
import { Request as ExpReq } from 'express'
import {
AnchorRequestParamsParser,
RequestAnchorParams,
} from '../anchor-request-params-parser.js'
import { AnchorRequestParamsParser, RequestAnchorParams } from '../anchor-request-params-parser.js'
import { StreamID } from '@ceramicnetwork/streamid'
import { toCID } from '@ceramicnetwork/common'
import { bases } from 'multiformats/basics'
Expand Down Expand Up @@ -42,9 +39,7 @@ const CAR_FILE_INVALID = mockRequest({
headers: {
'Content-Type': 'application/vnd.ipld.car',
},
body: bases['base64url'].decode(
'uQ3JlYXRlZEJ5Q2hhdEdQVDRZb3VjYW5Vc2VUaGlzU3RyaW5n'
),
body: bases['base64url'].decode('uQ3JlYXRlZEJ5Q2hhdEdQVDRZb3VjYW5Vc2VUaGlzU3RyaW5n'),
})

describe('AnchoRequestParamsParser', () => {
Expand All @@ -71,8 +66,7 @@ describe('AnchoRequestParamsParser', () => {
})

test('isleft indicates invalid car file', () => {
const validation = parser.parse(CAR_FILE_INVALID as ExpReq)
const validation = parser.parse(CAR_FILE_INVALID as ExpReq)
expect(isLeft(validation)).toBeTruthy()
})

})
1 change: 0 additions & 1 deletion src/ancillary/anchor-request-params-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ export class AnchorRequestCarFileDecoder implements Decoder<Uint8Array, RequestA
return context.failure(`Can not decode CAR file: ${message}`)
}
}

}

export class AnchorRequestParamsParser {
Expand Down
72 changes: 36 additions & 36 deletions src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,50 +16,50 @@ function buildExpressMiddleware() {
* Notice that the absense of a did header or body bypasses any checks below
* this app will still work if the logice above is not in place.
*/
return function(req: Request, _res: Response, next: NextFunction) {
if (req.headers) {
if (req.headers['did'] && req.body) {
if (Object.keys(req.body).length > 0) {
const digest = buildBodyDigest(req.headers['content-type'], req.body)
if (req.headers['digest'] == digest) {
return next()
} else {
throw Error('Body digest verification failed')
}
}
}
return function (req: Request, _res: Response, next: NextFunction) {
if (req.headers) {
if (req.headers['did'] && req.body) {
if (Object.keys(req.body).length > 0) {
const digest = buildBodyDigest(req.headers['content-type'], req.body)
if (req.headers['digest'] == digest) {
return next()
} else {
throw Error('Body digest verification failed')
}
}
return next()
}
}
return next()
}
}

function buildBodyDigest(contentType: string | undefined, body: any): string | undefined {
if (!body) return
if (!body) return

let hash: Uint8Array | undefined

if (contentType) {
if (contentType.includes('application/vnd.ipld.car')) {
const carFactory = new CARFactory()
carFactory.codecs.add(DAG_JOSE)
// console.log('Will build a car file from req.body', body)
// try {
// console.log('Will build a car file from req.body (as utf8 string)', u8a.toString(body, 'base64'))
// } catch(e) {
// console.log('Couldn\'t convert req.body to string: ', e)
// }
const car = carFactory.fromBytes(body)
if (!car.roots[0]) throw Error('Missing CAR root')
return car.roots[0].toString()
} else if (contentType.includes('application/json')) {
hash = sha256.hash(u8a.fromString(JSON.stringify(body)))
}
}
let hash: Uint8Array | undefined

if (!hash) {
// Default to hashing stringified body
if (contentType) {
if (contentType.includes('application/vnd.ipld.car')) {
const carFactory = new CARFactory()
carFactory.codecs.add(DAG_JOSE)
// console.log('Will build a car file from req.body', body)
// try {
// console.log('Will build a car file from req.body (as utf8 string)', u8a.toString(body, 'base64'))
// } catch(e) {
// console.log('Couldn\'t convert req.body to string: ', e)
// }
const car = carFactory.fromBytes(body)
if (!car.roots[0]) throw Error('Missing CAR root')
return car.roots[0].toString()
} else if (contentType.includes('application/json')) {
hash = sha256.hash(u8a.fromString(JSON.stringify(body)))
}
}

return `0x${u8a.toString(hash, 'base16')}`
if (!hash) {
// Default to hashing stringified body
hash = sha256.hash(u8a.fromString(JSON.stringify(body)))
}

return `0x${u8a.toString(hash, 'base16')}`
}
46 changes: 22 additions & 24 deletions src/controllers/__tests__/app-handler-chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ import { describe, expect, jest, test } from '@jest/globals'
import { CeramicAnchorServer } from '../../server.js'
import { logger } from '../../logger/index.js'
import request from 'supertest'
import { Config } from 'node-config-ts';
import { Config } from 'node-config-ts'

const FAUX_CONFIG = {
} as Config
const FAUX_CONFIG = {} as Config

describe('CeramicAnchorServer', () => {
describe('error handling middleware', () => {

test('should log errors with the express error logger when a controller throws an error', async () => {
// Define a mock controller with a GET route that throws an error
const error = new Error('Test error message')
Expand All @@ -18,40 +16,40 @@ describe('CeramicAnchorServer', () => {
router: {
get: jest.fn((req, res, next) => {
throw error
})
}
}),
},
}

// Create a new instance of CeramicAnchorServer with the mock controller and an empty config object
const server = new CeramicAnchorServer([mockController], FAUX_CONFIG);
const server = new CeramicAnchorServer([mockController], FAUX_CONFIG)

// spy on logger
const loggerSpy = jest.spyOn(logger, 'log');
const loggerSpy = jest.spyOn(logger, 'log')

// Call the server's start method to start listening for requests
await server.start();
await server.start()

// Use supertest to send a GET request to the mock controller's route
const response = await request(server.app).get('/mock');
const response = await request(server.app).get('/mock')

// Assert that the response status is 500
expect(response.status).toBe(500);
expect(response.status).toBe(500)

const errorData = {
type: 'error',
message: error.message,
stack: error.stack || '',
status: 500,
originalUrl: '/mock',
baseUrl: '',
path: '/mock',
sourceIp: '',
did: '',
type: 'error',
message: error.message,
stack: error.stack || '',
status: 500,
originalUrl: '/mock',
baseUrl: '',
path: '/mock',
sourceIp: '',
did: '',
}
expect(loggerSpy).toHaveBeenCalledWith(errorData)

// Stop the server
server.stop();
});
});
});
server.stop()
})
})
})
26 changes: 13 additions & 13 deletions src/logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,19 +80,19 @@ export const logMetric = {
}

interface ErrorData extends ServiceLog {
type: string;
message: string;
stack: string;
status: number;
originalUrl: string;
baseUrl: string;
path: string;
sourceIp: string;
did: string;
type: string
message: string
stack: string
status: number
originalUrl: string
baseUrl: string
path: string
sourceIp: string
did: string
}

export function expressErrorLogger(err: Error, req: ExpReq, res: ExpRes, next: ExpNext): void {
const logger = loggerProvider.makeServiceLogger('http-error');
const logger = loggerProvider.makeServiceLogger('http-error')
const errorData: ErrorData = {
type: 'error',
message: err.message,
Expand All @@ -103,8 +103,8 @@ export function expressErrorLogger(err: Error, req: ExpReq, res: ExpRes, next: E
path: req.path,
sourceIp: req.get('sourceIp') || '',
did: req.get('did') || '',
};
}

logger.log(errorData);
next(err);
logger.log(errorData)
next(err)
}
7 changes: 4 additions & 3 deletions src/merkle/merkle-car-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ import {
type Node,
type PathDirection,
type CIDHolder,
type TreeMetadata, CompareFunction,
type TreeMetadata,
CompareFunction,
} from '@ceramicnetwork/anchor-utils'
import type { Candidate } from '../services/candidate.js'
import type { CID } from 'multiformats/cid'
import type {ICandidate} from "@ceramicnetwork/anchor-utils";
import type { ICandidate } from '@ceramicnetwork/anchor-utils'

const carFactory = new CARFactory()
carFactory.codecs.add(DAG_JOSE)
Expand All @@ -24,7 +25,7 @@ carFactory.codecs.add(DAG_JOSE)
*/
class CIDSort implements CompareFunction<ICandidate> {
compare(left: Node<ICandidate>, right: Node<ICandidate>): number {
return left.data.cid.toString().localeCompare(right.data.cid.toString());
return left.data.cid.toString().localeCompare(right.data.cid.toString())
}
}

Expand Down
14 changes: 3 additions & 11 deletions src/repositories/request-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,7 @@ const recordAnchorRequestMetrics = (requests: Request[], anchoringDeadline: Date
* Injection factory.
*/
function make(config: Config, connection: Knex) {
return new RequestRepository(
connection,
config.maxAnchoringDelayMS,
config.readyRetryIntervalMS,
)
return new RequestRepository(connection, config.maxAnchoringDelayMS, config.readyRetryIntervalMS)
}
make.inject = ['config', 'dbConnection'] as const

Expand All @@ -89,19 +85,15 @@ export class RequestRepository {
constructor(
private readonly connection: Knex,
private readonly maxAnchoringDelayMS: number,
private readonly readyRetryIntervalMS: number,
private readonly readyRetryIntervalMS: number
) {}

get table() {
return this.connection(TABLE_NAME)
}

withConnection(connection: Knex): RequestRepository {
return new RequestRepository(
connection,
this.maxAnchoringDelayMS,
this.readyRetryIntervalMS,
)
return new RequestRepository(connection, this.maxAnchoringDelayMS, this.readyRetryIntervalMS)
}

/**
Expand Down
7 changes: 4 additions & 3 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { Server } from '@overnightjs/core'
import { auth } from './auth/index.js'
import { expressLoggers, logger, expressErrorLogger } from './logger/index.js'


import * as http from 'http'
import { Config } from 'node-config-ts'

Expand All @@ -16,9 +15,11 @@ export class CeramicAnchorServer extends Server {
super(true)

this.app.set('trust proxy', true)
this.app.use(bodyParser.raw({inflate: true, type: 'application/vnd.ipld.car', limit: '1mb'}))
this.app.use(bodyParser.raw({ inflate: true, type: 'application/vnd.ipld.car', limit: '1mb' }))
this.app.use(bodyParser.json({ type: 'application/json' }))
this.app.use(bodyParser.urlencoded({ extended: true, type: 'application/x-www-form-urlencoded' }))
this.app.use(
bodyParser.urlencoded({ extended: true, type: 'application/x-www-form-urlencoded' })
)
this.app.use(expressLoggers)
if (config.requireAuth == true) {
this.app.use(auth)
Expand Down
5 changes: 1 addition & 4 deletions src/services/__tests__/fake-factory.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ import { times } from '../../__tests__/test-utils.js'
* Generate fake data for testing purposes.
*/
export class FakeFactory {
constructor(
readonly ipfsService: IIpfsService,
readonly requestRepository: RequestRepository
) {}
constructor(readonly ipfsService: IIpfsService, readonly requestRepository: RequestRepository) {}

async streamId(): Promise<StreamID> {
const genesisCID = await this.ipfsService.storeRecord({
Expand Down
7 changes: 6 additions & 1 deletion src/services/anchor-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ import type { Knex } from 'knex'
import type { IIpfsService } from './ipfs-service.type.js'
import type { IAnchorRepository } from '../repositories/anchor-repository.type.js'
import { REPEATED_READ_SERIALIZATION_ERROR } from '../repositories/repository-types.js'
import {pathString, type CIDHolder, type TreeMetadata, ICandidateMetadata} from '@ceramicnetwork/anchor-utils'
import {
pathString,
type CIDHolder,
type TreeMetadata,
ICandidateMetadata,
} from '@ceramicnetwork/anchor-utils'
import { Candidate } from './candidate.js'
import { MerkleCarFactory, type IMerkleTree, type MerkleCAR } from '../merkle/merkle-car-factory.js'
import { IQueueConsumerService } from './queue/queue-service.type.js'
Expand Down
12 changes: 6 additions & 6 deletions src/services/merkle-car-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,12 @@ export class S3MerkleCarService implements IMerkleCarService {
if (!this._s3store) {
const levelDown = this.s3Endpoint
? new S3LevelDOWN(
this.s3StorePath,
new AWSSDK.S3({
endpoint: this.s3Endpoint,
s3ForcePathStyle: true,
})
)
this.s3StorePath,
new AWSSDK.S3({
endpoint: this.s3Endpoint,
s3ForcePathStyle: true,
})
)
: new S3LevelDOWN(this.s3StorePath)

this._s3store = new LevelUp(levelDown)
Expand Down
Loading

0 comments on commit 7115d46

Please sign in to comment.