|
| 1 | + |
| 2 | +/* |
| 3 | + * Copyright 2018 Expedia, Inc. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +import {Dispatcher} from './dispatcher'; |
| 19 | +import Span from '../span'; |
| 20 | +import { Logger, NullLogger } from '../logger'; |
| 21 | +import Utils from '../utils'; |
| 22 | +import {CoreOptions, Response} from 'request'; |
| 23 | +import * as request from 'request'; |
| 24 | + |
| 25 | +export default class HttpCollectorDispatcher implements Dispatcher { |
| 26 | + _collectorUrl: string; |
| 27 | + _headers: { [key: string]: any }; |
| 28 | + _logger: Logger; |
| 29 | + |
| 30 | + constructor(_collectorUrl: string = 'http://localhost:8080/span', headers: { [key: string]: any } = {}, logger: Logger = new NullLogger()) { |
| 31 | + this._collectorUrl = _collectorUrl; |
| 32 | + this._headers = headers; |
| 33 | + this._logger = logger; |
| 34 | + this._logger.info(`Initializing the http collector dispatcher, connecting at ${_collectorUrl}`); |
| 35 | + } |
| 36 | + |
| 37 | + name(): string { |
| 38 | + return 'HttpCollectorDispatcher'; |
| 39 | + } |
| 40 | + |
| 41 | + dispatch(span: Span, callback: (error) => void): void { |
| 42 | + const serializedSpanBuffer = Utils.convertToProtoSpan(span).serializeBinary(); |
| 43 | + const options: CoreOptions = {}; |
| 44 | + options.headers = this._headers; |
| 45 | + options.body = serializedSpanBuffer; |
| 46 | + request.post(this._collectorUrl, options, (error: any, response: Response, body: any) => { |
| 47 | + if (error) { |
| 48 | + this._logger.error(`Fail to dipatch to http collector with error ${error}`); |
| 49 | + return; |
| 50 | + } |
| 51 | + if (response.statusCode < 200 || response.statusCode >= 300) { |
| 52 | + this._logger.error(`Fail to dispatch to http collector with statusCode ${response.statusCode} and response ${body}`); |
| 53 | + return; |
| 54 | + } |
| 55 | + this._logger.debug(`successfully submitted the span to http collector with http response: ${body}`); |
| 56 | + }); |
| 57 | + } |
| 58 | + |
| 59 | + close(callback: () => void): void { |
| 60 | + if (callback) { |
| 61 | + callback(); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments