How to use @creditkarma/thrift-server-core - 10 common examples

To help you get started, we’ve selected a few @creditkarma/thrift-server-core examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github creditkarma / thrift-server / packages / thrift-server-hapi / src / main / ThriftServerHapi.ts View on Github external
)
                                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
                            }
github creditkarma / thrift-server / packages / thrift-client / src / main / connections / index.ts View on Github external
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)
}
github creditkarma / thrift-server / packages / zipkin-tracing-hapi / src / main / ZipkinTracingHapi.ts View on Github external
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) {
github creditkarma / thrift-server / packages / thrift-client / src / main / connections / HttpConnection.ts View on Github external
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(
github alitelabs / tyx / src / core / thrift.ts View on Github external
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;
  }
}
github guardian / editions / projects / backend / capi / articles.ts View on Github external
}
        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)
github guardian / editions / projects / backend / capi / articles.ts View on Github external
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)
}
github creditkarma / thrift-server / packages / thrift-integration / src / client / connections / TcpConnection.spec.ts View on Github external
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()
            })
        })
    })
github creditkarma / thrift-server / packages / thrift-client-ttwitter-filter / src / main / ThriftClientTTwitterFilter.ts View on Github external
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',
github creditkarma / thrift-server / packages / thrift-client / src / ttwitter / com / creditkarma / finagle / thrift / index.ts View on Github external
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();