Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
)
const metadata: Core.IThriftMessage = input.readMessageBegin()
const fieldName: string = metadata.fieldName
const requestId: number = metadata.requestId
const output: Core.TProtocol = new Protocol(
new Transport(),
)
const exception: Core.TApplicationException = new Core.TApplicationException(
Core.TApplicationExceptionType.INTERNAL_ERROR,
response.message as string, // If we're dealing with an error this is an Error not a Response
)
output.writeMessageBegin(
fieldName,
Core.MessageType.EXCEPTION,
requestId,
)
Core.TApplicationExceptionCodec.encode(
exception,
output,
)
output.writeMessageEnd()
return reply.response(output.flush()).code(500)
} catch (err) {
logger(
['error', 'ThriftServerHapi'],
`Unable to build TApplicationException for response error: ${err.message}`,
)
return reply.continue
}
options: ICreateHttpClientOptions,
): TClient {
let serviceName: string = ''
if ((ServiceClient as any).serviceName !== 'undefined') {
serviceName = (ServiceClient as any).serviceName
} else {
const nullConnection: NullConnection = new NullConnection(
BufferedTransport,
BinaryProtocol,
)
const nullClient: TClient = new ServiceClient(nullConnection)
serviceName = nullClient._serviceName
}
const connection: HttpConnection = new HttpConnection(
deepMerge(options, { serviceName }),
)
// Register optional middleware
connection.register(...(options.register || []))
return new ServiceClient(connection)
}
return tracer.scoped(() => {
const traceId: TraceId = instrumentation.recordRequest(
requestMethod,
Core.formatUrl(url.format(request.url)),
(header: string): option.IOption => {
const val = normalHeaders[header.toLowerCase()]
if (val !== null && val !== undefined) {
return new option.Some(val)
} else {
return option.None
}
},
)
const traceHeaders: Core.IRequestHeaders = headersForTraceId(
traceId,
)
// Update headers on request object
for (const key in traceHeaders) {
private write(
dataToWrite: Buffer,
methodName: string,
options: RequestOptions = {},
retry: boolean = false,
): Promise {
const requestUrl: string =
this.withEndpointPerMethod && retry === false
? `${this.url}/${this.serviceName}/${methodName}`
: this.url
// Merge user options with required options
const requestOptions: RequestOptions & UrlOptions = Core.overlayObjects(
this.requestOptions,
options,
{
method: 'POST',
body: dataToWrite,
encoding: null, // Needs to be explicitly set to null to get Buffer in response body
url: requestUrl,
headers: {
'Content-Length': dataToWrite.length,
'Content-Type': 'application/octet-stream',
},
},
)
return new Promise((resolve, reject) => {
request(
public async execute(req: HttpRequest, ctx: ThriftContext): Promise {
const buffer: Buffer = Buffer.from(req.buffer); // await rawBody(context.req);
const method: string = readThriftMethod(buffer, this.transport, this.protocol);
ctx.thrift = {
requestMethod: method,
processor: this.pluginOptions.handler,
transport: this.pluginOptions.transport || 'buffered',
protocol: this.pluginOptions.protocol || 'binary',
};
const result = await process({
processor: this.pluginOptions.handler,
buffer,
Transport: this.transport,
Protocol: this.protocol,
context: ctx
});
return result;
}
}
}
if (hasFailed(last)) {
console.error(last.error)
throw new Error('Error when spliting CAPI request (second half)')
}
const firstArray = Object.entries(first)
const lastArray = Object.entries(last)
return fromPairs(firstArray.concat(lastArray))
}
console.log('Making CAPI query', endpoint)
console.log('Debug link:', endpoint.replace(/thrift/g, 'json'))
const resp = await attempt(fetch(endpoint))
if (hasFailed(resp)) throw new Error('Could not connect to CAPI.')
const buffer = await resp.arrayBuffer()
const receiver: BufferedTransport = BufferedTransport.receiver(
Buffer.from(buffer),
)
const input = new CompactProtocol(receiver)
const data = SearchResponseCodec.decode(input)
const results: IContent[] = data.results
const articlePromises = await Promise.all(
results.map(result => attempt(parseArticleResult(result, isFromPrint))),
)
//If we fail to get an article in a collection we just ignore it and move on.
articlePromises.forEach(attempt => {
if (hasFailed(attempt)) {
console.log('failure when parsing', attempt.error)
}
})
const articleEntries = articlePromises.filter(hasSucceeded)
throw new Error('Error when spliting CAPI request (second half)')
}
const firstArray = Object.entries(first)
const lastArray = Object.entries(last)
return fromPairs(firstArray.concat(lastArray))
}
console.log('Making CAPI query', endpoint)
console.log('Debug link:', endpoint.replace(/thrift/g, 'json'))
const resp = await attempt(fetch(endpoint))
if (hasFailed(resp)) throw new Error('Could not connect to CAPI.')
const buffer = await resp.arrayBuffer()
const receiver: BufferedTransport = BufferedTransport.receiver(
Buffer.from(buffer),
)
const input = new CompactProtocol(receiver)
const data = SearchResponseCodec.decode(input)
const results: IContent[] = data.results
const articlePromises = await Promise.all(
results.map(result => attempt(parseArticleResult(result, isFromPrint))),
)
//If we fail to get an article in a collection we just ignore it and move on.
articlePromises.forEach(attempt => {
if (hasFailed(attempt)) {
console.log('failure when parsing', attempt.error)
}
})
const articleEntries = articlePromises.filter(hasSucceeded)
return fromPairs(articleEntries)
}
import { ISharedStruct, ISharedUnion } from '../../generated/shared'
import { IMetadata, MetadataCodec } from '../../generated/common'
import { APACHE_SERVER_CONFIG } from '../../config'
export const lab = Lab.script()
const describe = lab.describe
const it = lab.it
const before = lab.before
const after = lab.after
const afterEach = lab.afterEach
const frameCodec: thrift.ThriftFrameCodec = new thrift.ThriftFrameCodec()
describe('TcpConnection', () => {
let server: net.Server
before(async () => {
return new Promise((resolve, reject) => {
server = createServer()
server.listen(APACHE_SERVER_CONFIG.port, 'localhost', () => {
console.log(
`TCP server running on port[${APACHE_SERVER_CONFIG.port}]`,
)
resolve()
})
})
})
formatUrl(request.uri),
request.methodName || 'post',
)
const normalHeaders: any = Object.keys(
headers,
).reduce((acc: any, name: string) => {
acc[name.toLowerCase()] = headers[name]
return acc
}, {})
const requestHeader: TTwitter.IRequestHeader = {
trace_id: new Int64(
`0x${normalHeaders[ZipkinHeaders.TraceId]}`,
),
span_id: new Int64(
`0x${normalHeaders[ZipkinHeaders.SpanId]}`,
),
parent_span_id:
normalHeaders[ZipkinHeaders.ParentId] !==
undefined
? new Int64(
`0x${
normalHeaders[
ZipkinHeaders.ParentId
]
}`,
)
: undefined,
sampled:
normalHeaders[ZipkinHeaders.Sampled] ===
'1',
constructor(args: ISpanArgs = {}) {
super();
if (args.trace_id != null) {
const value_32: thrift.Int64 = (typeof args.trace_id === "number" ? new thrift.Int64(args.trace_id) : args.trace_id);
this.trace_id = value_32;
}
if (args.name != null) {
const value_33: string = args.name;
this.name = value_33;
}
if (args.id != null) {
const value_34: thrift.Int64 = (typeof args.id === "number" ? new thrift.Int64(args.id) : args.id);
this.id = value_34;
}
if (args.parent_id != null) {
const value_35: thrift.Int64 = (typeof args.parent_id === "number" ? new thrift.Int64(args.parent_id) : args.parent_id);
this.parent_id = value_35;
}
if (args.annotations != null) {
const value_36: Array = new Array();