Skip to content

Commit

Permalink
[Monitor] use core-http (Azure#10615)
Browse files Browse the repository at this point in the history
  • Loading branch information
markwolff authored Aug 13, 2020
1 parent dcd91bb commit ad2560e
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 134 deletions.
1 change: 1 addition & 0 deletions sdk/monitor/opentelemetry-exporter/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"typescript": "~3.9.3"
},
"dependencies": {
"@azure/core-http": "^1.1.6",
"@opentelemetry/api": "^0.10.2",
"@opentelemetry/core": "^0.10.1",
"@opentelemetry/semantic-conventions": "^0.10.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,67 +1,55 @@
import * as http from "http";
import * as zlib from "zlib";
import { Logger } from "@opentelemetry/api";
import { ConsoleLogger, LogLevel } from "@opentelemetry/core";
import { Sender, SenderCallback } from "../../types";
import { Envelope } from "../../Declarations/Contracts";
import { DEFAULT_SENDER_OPTIONS, NodejsPlatformConfig } from "../types";
import { makeRequest } from "./utils/httpUtils";
import { promisify } from "util";
import { DefaultHttpClient, HttpClient, HttpHeaders, WebResource } from "@azure/core-http";

const gzipAsync = promisify<zlib.InputType, Buffer>(zlib.gzip);

export class HttpSender implements Sender {
private readonly _logger: Logger;

private readonly _httpClient: HttpClient;

constructor(private _options: NodejsPlatformConfig = DEFAULT_SENDER_OPTIONS) {
this._logger = _options.logger || new ConsoleLogger(LogLevel.ERROR);
this._httpClient = new DefaultHttpClient();
}

send(envelopes: Envelope[], callback: SenderCallback = () => {}): void {
async send(envelopes: Envelope[], callback: SenderCallback = () => {}): Promise<void> {
const endpointUrl = `${this._options.endpointUrl}/v2/track`;
const payload = Buffer.from(JSON.stringify(envelopes));

// todo: investigate specifying an agent here: https://nodejs.org/api/http.html#http_class_http_agent
const options = {
method: "POST",
withCredentials: false,
headers: <{ [key: string]: string }>{
"Content-Type": "application/x-json-stream",
},
};

zlib.gzip(payload, (err, buffer) => {
let dataToSend = buffer;
if (err) {
this._logger.warn(`Failed to gzip payload: ${err.message}. Sending payload uncompressed`);
dataToSend = payload; // something went wrong so send without gzip
options.headers["Content-Length"] = payload.length.toString();
} else {
options.headers["Content-Encoding"] = "gzip";
options.headers["Content-Length"] = String(buffer.length);
}

this._logger.debug(`HTTPS Options:`, options);

const requestCallback = (res: http.IncomingMessage) => {
res.setEncoding("utf-8");

// returns empty if the data is accepted
let responseString = "";
res.on("data", (data: string) => {
responseString += data;
});

res.on("end", () => {
this._logger.info(`Azure HTTP response: ${responseString}`);
callback(null, res.statusCode, responseString);
});
};

const req = makeRequest(this._options, endpointUrl, options, requestCallback);

req.on("error", callback);

req.write(dataToSend);
req.end();
});
const headers = new HttpHeaders({ "Content-Type": "application/x-json-stream" });

let dataToSend: Buffer;
try {
dataToSend = await gzipAsync(payload);
headers.set("Content-Encoding", "gzip");
} catch (err) {
this._logger.warn(`Failed to gzip payload: ${err.message}. Sending payload uncompressed`);
dataToSend = payload; // something went wrong so send without gzip
}
headers.set("Content-Length", dataToSend.length);

const options = new WebResource(
endpointUrl,
"POST",
dataToSend,
undefined,
headers,
undefined,
false // withCredentials: false
);
try {
const res = await this._httpClient.sendRequest(options);
callback(null, res.status, res.bodyAsText || "");
} catch (err) {
callback(err);
}
}

shutdown(): void {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,17 @@ import { DEFAULT_BREEZE_ENDPOINT } from "../../../src/Declarations/Constants";
import {
successfulBreezeResponse,
failedBreezeResponse,
partialBreezeResponse,
partialBreezeResponse
} from "../../breezeTestUtils";
import nock = require("nock");

describe("HttpSender", () => {
const scope = nock(DEFAULT_BREEZE_ENDPOINT).post("/v2/track");
nock.disableNetConnect();

after(() => {
nock.cleanAll();
nock.enableNetConnect();
});

describe("#constructor", () => {
Expand Down

0 comments on commit ad2560e

Please sign in to comment.