Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#176082784] Add keepalive to notification hub client #135

Merged
merged 2 commits into from
Dec 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions HandleNHNotificationCallActivity/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { toString } from "fp-ts/lib/function";
import { readableReport } from "italia-ts-commons/lib/reporters";

import { toError } from "fp-ts/lib/Either";
import { fromEither } from "fp-ts/lib/TaskEither";
import { fromEither, taskEither } from "fp-ts/lib/TaskEither";
import { KindEnum as CreateOrUpdateKind } from "../generated/notifications/CreateOrUpdateInstallationMessage";
import { KindEnum as DeleteKind } from "../generated/notifications/DeleteInstallationMessage";
import { KindEnum as NotifyKind } from "../generated/notifications/NotifyMessage";
Expand All @@ -17,6 +17,8 @@ import {
notify
} from "../utils/notification";

import { initTelemetryClient } from "../utils/appinsights";

// Activity input
export const ActivityInput = t.interface({
message: NotificationMessage
Expand Down Expand Up @@ -72,6 +74,8 @@ const assertNever = (x: never): never => {
throw new Error(`Unexpected object: ${toString(x)}`);
};

const telemetryClient = initTelemetryClient();

/**
* For each Notification Hub Message calls related Notification Hub service
*/
Expand All @@ -98,9 +102,22 @@ export const getCallNHServiceActivityHandler = (
retryActivity(context, `${logPrefix}|ERROR=${toString(e)}`)
);
case NotifyKind.Notify:
return notify(message.installationId, message.payload).mapLeft(e =>
retryActivity(context, `${logPrefix}|ERROR=${toString(e)}`)
);
return notify(message.installationId, message.payload)
.mapLeft(e =>
retryActivity(context, `${logPrefix}|ERROR=${toString(e)}`)
)
.chainFirst(
taskEither.of(
telemetryClient.trackEvent({
name: "api.messages.notification.push.sent",
properties: {
isSuccess: "true",
messageId: message.payload.message_id
},
tagOverrides: { samplingEnabled: "false" }
})
)
);
case DeleteKind.DeleteInstallation:
return deleteInstallation(message.installationId).mapLeft(e => {
// do not trigger a retry as delete may fail in case of 404
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"jest-mock-express": "^0.1.1",
"lolex": "^5.1.1",
"modclean": "^3.0.0-beta.1",
"nock": "^13.0.5",
"npm-run-all": "^4.1.5",
"prettier": "^1.18.2",
"shx": "^0.3.2",
Expand Down
39 changes: 39 additions & 0 deletions utils/__tests__/notification.keepalive.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// tslint:disable-next-line: no-object-mutation
process.env = {
...process.env,
AZURE_NH_ENDPOINT:
"Endpoint=sb://127.0.0.1:30000;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=foobar",
AZURE_NH_HUB_NAME: "io-notification-hub-mock",
FETCH_KEEPALIVE_ENABLED: "true",
FETCH_KEEPALIVE_FREE_SOCKET_TIMEOUT: "30000",
FETCH_KEEPALIVE_MAX_FREE_SOCKETS: "10",
FETCH_KEEPALIVE_MAX_SOCKETS: "40",
FETCH_KEEPALIVE_SOCKET_ACTIVE_TTL: "110000",
FETCH_KEEPALIVE_TIMEOUT: "60000"
};

import { NonEmptyString } from "italia-ts-commons/lib/strings";
import * as nock from "nock";
import { notify } from "../notification";

describe("NotificationHubService", () => {
it("should use agentkeepalive when calling notification hub", async () => {
const responseSpy = jest.fn();
nock("https://127.0.0.1:30000")
.post(_ => true)
// tslint:disable-next-line: typedef
.reply(function() {
// tslint:disable-next-line: no-tslint-disable-all
// tslint:disable-next-line
responseSpy((this.req as any).options.agent.options.maxSockets);
});
await notify("x" as NonEmptyString, {
message: "foo",
message_id: "bar",
title: "beef"
}).run();
expect(responseSpy).toHaveBeenCalledWith(
parseInt(process.env.FETCH_KEEPALIVE_MAX_SOCKETS, 10)
);
});
});
31 changes: 31 additions & 0 deletions utils/__tests__/notification.vanilla.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// tslint:disable-next-line: no-object-mutation
process.env = {
...process.env,
AZURE_NH_ENDPOINT:
"Endpoint=sb://127.0.0.1:30000;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=foobar",
AZURE_NH_HUB_NAME: "io-notification-hub-mock"
};

import { NonEmptyString } from "italia-ts-commons/lib/strings";
import * as nock from "nock";
import { notify } from "../notification";

describe("NotificationHubService", () => {
it("should not use agentkeepalive when calling notification hub", async () => {
const responseSpy = jest.fn();
nock("https://127.0.0.1:30000")
.post(_ => true)
// tslint:disable-next-line: typedef
.reply(function() {
// tslint:disable-next-line: no-tslint-disable-all
// tslint:disable-next-line
responseSpy((this.req as any).options.agent.options.maxSockets);
});
await notify("x" as NonEmptyString, {
message: "foo",
message_id: "bar",
title: "beef"
}).run();
expect(responseSpy).toHaveBeenCalledWith(undefined);
});
});
43 changes: 41 additions & 2 deletions utils/notification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@
import * as t from "io-ts";
import { NonEmptyString } from "italia-ts-commons/lib/strings";

import * as azure from "azure-sb";
import { NotificationHubService } from "azure-sb";
import { tryCatch } from "fp-ts/lib/TaskEither";
import {
getKeepAliveAgentOptions,
newHttpsAgent
} from "italia-ts-commons/lib/agent";
import { Platform, PlatformEnum } from "../generated/backend/Platform";
import { getConfigOrThrow } from "../utils/config";

Expand Down Expand Up @@ -37,7 +41,42 @@ export enum APNSPushType {

const config = getConfigOrThrow();

const notificationHubService = azure.createNotificationHubService(
const httpsAgent = newHttpsAgent(getKeepAliveAgentOptions(process.env));

// Monkey patch azure-sb package in order to use agentkeepalive
// when calling the Notification Hub API.
// @FIXME: remove this part and upgrade to @azure/notification-hubs
// once this goes upstream: https://github.com/Azure/azure-sdk-for-js/pull/11977
class ExtendedNotificationHubService extends NotificationHubService {
constructor(hubName: string, endpointOrConnectionString: string) {
super(hubName, endpointOrConnectionString, undefined, undefined);
}
// tslint:disable-next-line: typedef
public _buildRequestOptions(
webResource: unknown,
body: unknown,
options: unknown,
// tslint:disable-next-line: ban-types
cb: Function
) {
// tslint:disable-next-line: no-any
const patchedCallback = (err: any, cbOptions: any) => {
cb(err, {
...cbOptions,
agent: httpsAgent
});
};
// tslint:disable-next-line: no-string-literal
return super["_buildRequestOptions"](
webResource,
body,
options,
patchedCallback
);
}
}

const notificationHubService = new ExtendedNotificationHubService(
config.AZURE_NH_HUB_NAME,
config.AZURE_NH_ENDPOINT
);
Expand Down
20 changes: 20 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4936,6 +4936,11 @@ lodash.once@^4.0.0:
resolved "https://registry.yarnpkg.com/lodash.once/-/lodash.once-4.1.1.tgz#0dd3971213c7c56df880977d504c88fb471a97ac"
integrity sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=

lodash.set@^4.3.2:
version "4.3.2"
resolved "https://registry.yarnpkg.com/lodash.set/-/lodash.set-4.3.2.tgz#d8757b1da807dde24816b0d6a84bea1a76230b23"
integrity sha1-2HV7HagH3eJIFrDWqEvqGnYjCyM=

lodash.sortby@^4.7.0:
version "4.7.0"
resolved "https://registry.yarnpkg.com/lodash.sortby/-/lodash.sortby-4.7.0.tgz#edd14c824e2cc9c1e0b0a1b42bb5210516a42438"
Expand Down Expand Up @@ -5390,6 +5395,16 @@ nocache@2.1.0:
resolved "https://registry.yarnpkg.com/nocache/-/nocache-2.1.0.tgz#120c9ffec43b5729b1d5de88cd71aa75a0ba491f"
integrity sha512-0L9FvHG3nfnnmaEQPjT9xhfN4ISk0A8/2j4M37Np4mcDesJjHgEUfgPhdCyZuFI954tjokaIj/A3NdpFNdEh4Q==

nock@^13.0.5:
version "13.0.5"
resolved "https://registry.yarnpkg.com/nock/-/nock-13.0.5.tgz#a618c6f86372cb79fac04ca9a2d1e4baccdb2414"
integrity sha512-1ILZl0zfFm2G4TIeJFW0iHknxr2NyA+aGCMTjDVUsBY4CkMRispF1pfIYkTRdAR/3Bg+UzdEuK0B6HczMQZcCg==
dependencies:
debug "^4.1.0"
json-stringify-safe "^5.0.1"
lodash.set "^4.3.2"
propagate "^2.0.0"

node-abort-controller@^1.0.4:
version "1.1.0"
resolved "https://registry.yarnpkg.com/node-abort-controller/-/node-abort-controller-1.1.0.tgz#8a734a631b022af29963be7245c1483cbb9e070d"
Expand Down Expand Up @@ -6130,6 +6145,11 @@ prompts@^2.0.1:
kleur "^3.0.2"
sisteransi "^1.0.0"

propagate@^2.0.0:
version "2.0.1"
resolved "https://registry.yarnpkg.com/propagate/-/propagate-2.0.1.tgz#40cdedab18085c792334e64f0ac17256d38f9a45"
integrity sha512-vGrhOavPSTz4QVNuBNdcNXePNdNMaO1xj9yBeH1ScQPjk/rhg9sSlCXPhMkFuaNNW/syTvYqsnbIJxMBfRbbag==

property-information@^3.1.0:
version "3.2.0"
resolved "https://registry.yarnpkg.com/property-information/-/property-information-3.2.0.tgz#fd1483c8fbac61808f5fe359e7693a1f48a58331"
Expand Down