Skip to content

Commit

Permalink
Update with changes from main, remove frequent duplicate events optio…
Browse files Browse the repository at this point in the history
…n. (#75)
  • Loading branch information
kinyoklion authored Sep 28, 2022
1 parent 2d7056b commit c6ca9d2
Show file tree
Hide file tree
Showing 20 changed files with 363 additions and 147 deletions.
2 changes: 1 addition & 1 deletion .ldrelease/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ repo:
private: js-sdk-common-private

branches:
- name: master
- name: main
description: 4.x
- name: 3.x

Expand Down
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@

All notable changes to the `launchdarkly-js-sdk-common` package will be documented in this file. Changes that affect the dependent SDKs such as `launchdarkly-js-client-sdk` should also be logged in those projects, in the next release that uses the updated version of this package. This project adheres to [Semantic Versioning](http://semver.org).

## [4.1.1] - 2022-06-07
### Changed:
- Enforce a 64 character limit for `application.id` and `application.version` configuration options.

### Fixed:
- Do not include deleted flags in `allFlags`.

## [4.1.0] - 2022-04-21
### Added:
- `LDOptionsBase.application`, for configuration of application metadata that may be used in LaunchDarkly analytics or other product features. This does not affect feature flag evaluations.

### Fixed:
- The `baseUrl`, `streamUrl`, and `eventsUrl` properties now work properly regardless of whether the URL string has a trailing slash. Previously, a trailing slash would cause request URL paths to have double slashes.

## [4.0.3] - 2022-02-16
### Fixed:
- If the SDK receives invalid JSON data from a streaming connection (possibly as a result of the connection being cut off), it now uses its regular error-handling logic: the error is emitted as an `error` event or, if there are no `error` event listeners, it is logged. Previously, it would be thrown as an unhandled exception.
Expand All @@ -23,6 +37,10 @@ All notable changes to the `launchdarkly-js-sdk-common` package will be document
- Removed the type `NonNullableLDEvaluationReason`, which was a side effect of the `LDEvaluationDetail.reason` being incorrectly defined before.
- Removed all types, properties, and functions that were deprecated as of the last 3.x release.

## [3.5.1] - 2022-02-17
### Fixed:
- If the SDK receives invalid JSON data from a streaming connection (possibly as a result of the connection being cut off), it now uses its regular error-handling logic: the error is emitted as an `error` event or, if there are no `error` event listeners, it is logged. Previously, it would be thrown as an unhandled exception.

## [3.5.0] - 2022-01-14
### Added:
- New configurable logger factory `commonBasicLogger` and `BasicLoggerOptions`. The `commonBasicLogger` method is not intended to be exported directly in the SDKs, but wrapped to provide platform-specific behavior.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "launchdarkly-js-sdk-common",
"version": "4.0.3",
"version": "4.1.1",
"description": "LaunchDarkly SDK for JavaScript - common code",
"author": "LaunchDarkly <team@launchdarkly.com>",
"license": "Apache-2.0",
Expand Down
2 changes: 1 addition & 1 deletion src/EventProcessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ function EventProcessor(
) {
const processor = {};
const eventSender = sender || EventSender(platform, environmentId, options);
const mainEventsUrl = options.eventsUrl + '/events/bulk/' + environmentId;
const mainEventsUrl = utils.appendUrlPath(options.eventsUrl, '/events/bulk/' + environmentId);
const summarizer = EventSummarizer();
const contextFilter = ContextFilter(options);
const samplingInterval = options.samplingInterval;
Expand Down
5 changes: 3 additions & 2 deletions src/EventSender.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
const errors = require('./errors');
const utils = require('./utils');
const { v1: uuidv1 } = require('uuid');
const { getLDHeaders, transformHeaders } = require('./headers');

const MAX_URL_LENGTH = 2000;

function EventSender(platform, environmentId, options) {
const imageUrlPath = '/a/' + environmentId + '.gif';
const baseHeaders = utils.extend({ 'Content-Type': 'application/json' }, utils.getLDHeaders(platform, options));
const baseHeaders = utils.extend({ 'Content-Type': 'application/json' }, getLDHeaders(platform, options));
const httpFallbackPing = platform.httpFallbackPing; // this will be set for us if we're in the browser SDK
const sender = {};

Expand Down Expand Up @@ -34,7 +35,7 @@ function EventSender(platform, environmentId, options) {
'X-LaunchDarkly-Payload-ID': payloadId,
});
return platform
.httpRequest('POST', url, utils.transformHeaders(headers, options), jsonBody)
.httpRequest('POST', url, transformHeaders(headers, options), jsonBody)
.promise.then(result => {
if (!result) {
// This was a response from a fire-and-forget request, so we won't have a status.
Expand Down
7 changes: 4 additions & 3 deletions src/Requestor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const utils = require('./utils');
const errors = require('./errors');
const messages = require('./messages');
const promiseCoalescer = require('./promiseCoalescer');
const { transformHeaders, getLDHeaders } = require('./headers');

const jsonContentType = 'application/json';

Expand Down Expand Up @@ -31,7 +32,7 @@ function Requestor(platform, options, environment) {
}

const method = body ? 'REPORT' : 'GET';
const headers = utils.getLDHeaders(platform, options);
const headers = getLDHeaders(platform, options);
if (body) {
headers['Content-Type'] = jsonContentType;
}
Expand All @@ -45,7 +46,7 @@ function Requestor(platform, options, environment) {
activeRequests[endpoint] = coalescer;
}

const req = platform.httpRequest(method, endpoint, utils.transformHeaders(headers, options), body);
const req = platform.httpRequest(method, endpoint, transformHeaders(headers, options), body);
const p = req.promise.then(
result => {
if (result.status === 200) {
Expand Down Expand Up @@ -75,7 +76,7 @@ function Requestor(platform, options, environment) {
// Performs a GET request to an arbitrary path under baseUrl. Returns a Promise which will resolve
// with the parsed JSON response, or will be rejected if the request failed.
requestor.fetchJSON = function(path) {
return fetchJSON(baseUrl + path, null);
return fetchJSON(utils.appendUrlPath(baseUrl, path), null);
};

// Requests the current state of all flags for the given context from LaunchDarkly. Returns a Promise
Expand Down
7 changes: 4 additions & 3 deletions src/Stream.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const messages = require('./messages');
const { base64URLEncode, getLDHeaders, transformHeaders, objectHasOwnProperty } = require('./utils');
const { appendUrlPath, base64URLEncode, objectHasOwnProperty } = require('./utils');
const { getLDHeaders, transformHeaders } = require('./headers');

// The underlying event source implementation is abstracted via the platform object, which should
// have these three properties:
Expand All @@ -20,7 +21,7 @@ function Stream(platform, config, environment, diagnosticsAccumulator) {
const baseUrl = config.streamUrl;
const logger = config.logger;
const stream = {};
const evalUrlPrefix = baseUrl + '/eval/' + environment;
const evalUrlPrefix = appendUrlPath(baseUrl, '/eval/' + environment);
const useReport = config.useReport;
const withReasons = config.evaluationReasons;
const streamReconnectDelay = config.streamReconnectDelay;
Expand Down Expand Up @@ -98,7 +99,7 @@ function Stream(platform, config, environment, diagnosticsAccumulator) {
options.body = JSON.stringify(context);
} else {
// if we can't do REPORT, fall back to the old ping-based stream
url = baseUrl + '/ping/' + environment;
url = appendUrlPath(baseUrl, '/ping/' + environment);
query = '';
}
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/__tests__/Stream-test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { DiagnosticsAccumulator } from '../diagnosticEvents';
import * as messages from '../messages';
import Stream from '../Stream';
import { getLDHeaders } from '../utils';
import { getLDHeaders } from '../headers';

import { sleepAsync } from 'launchdarkly-js-test-helpers';
import EventSource from './EventSource-mock';
Expand Down
47 changes: 46 additions & 1 deletion src/__tests__/configuration-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ describe('configuration', () => {
checkBooleanProperty('sendEvents');
checkBooleanProperty('allAttributesPrivate');
checkBooleanProperty('sendLDHeaders');
checkBooleanProperty('allowFrequentDuplicateEvents');
checkBooleanProperty('sendEventsOnlyForVariation');
checkBooleanProperty('useReport');
checkBooleanProperty('evaluationReasons');
Expand Down Expand Up @@ -213,4 +212,50 @@ describe('configuration', () => {
expect(config.extraFunctionOption).toBe(fn);
await listener.expectError(messages.wrongOptionType('extraNumericOptionWithoutDefault', 'number', 'string'));
});

it('handles a valid application id', async () => {
const listener = errorListener();
const configIn = { application: { id: 'test-application' } };
expect(configuration.validate(configIn, listener.emitter, null, listener.logger).application.id).toEqual(
'test-application'
);
});

it('logs a warning with an invalid application id', async () => {
const listener = errorListener();
const configIn = { application: { id: 'test #$#$#' } };
expect(configuration.validate(configIn, listener.emitter, null, listener.logger).application.id).toBeUndefined();
await listener.expectWarningOnly(messages.invalidTagValue('application.id'));
});

it('logs a warning when a tag value is too long', async () => {
const listener = errorListener();
const configIn = { application: { id: 'a'.repeat(65), version: 'b'.repeat(64) } };
expect(configuration.validate(configIn, listener.emitter, null, listener.logger).application.id).toBeUndefined();
await listener.expectWarningOnly(messages.tagValueTooLong('application.id'));
});

it('handles a valid application version', async () => {
const listener = errorListener();
const configIn = { application: { version: 'test-version' } };
expect(configuration.validate(configIn, listener.emitter, null, listener.logger).application.version).toEqual(
'test-version'
);
});

it('logs a warning with an invalid application version', async () => {
const listener = errorListener();
const configIn = { application: { version: 'test #$#$#' } };
expect(
configuration.validate(configIn, listener.emitter, null, listener.logger).application.version
).toBeUndefined();
await listener.expectWarningOnly(messages.invalidTagValue('application.version'));
});

it('includes application id and version in tags when present', async () => {
expect(configuration.getTags({ application: { id: 'test-id', version: 'test-version' } })).toEqual({
'application-id': ['test-id'],
'application-version': ['test-version'],
});
});
});
2 changes: 0 additions & 2 deletions src/__tests__/diagnosticEvents-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ describe('DiagnosticsManager', () => {
};
const defaultConfigInEvent = {
allAttributesPrivate: false,
allowFrequentDuplicateEvents: false,
bootstrapMode: false,
customBaseURI: false,
customEventsURI: false,
Expand Down Expand Up @@ -187,7 +186,6 @@ describe('DiagnosticsManager', () => {
it('sends init event on start() with custom config', async () => {
const configAndResultValues = [
[{ allAttributesPrivate: true }, { allAttributesPrivate: true }],
[{ allowFrequentDuplicateEvents: true }, { allowFrequentDuplicateEvents: true }],
[{ bootstrap: {} }, { bootstrapMode: true }],
[{ baseUrl: 'http://other' }, { customBaseURI: true }],
[{ eventsUrl: 'http://other' }, { customEventsURI: true }],
Expand Down
117 changes: 117 additions & 0 deletions src/__tests__/headers-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { getLDHeaders, transformHeaders } from '../headers';
import { getLDUserAgentString } from '../utils';
import * as stubPlatform from './stubPlatform';

describe('getLDHeaders', () => {
it('sends no headers unless sendLDHeaders is true', () => {
const platform = stubPlatform.defaults();
const headers = getLDHeaders(platform, {});
expect(headers).toEqual({});
});

it('adds user-agent header', () => {
const platform = stubPlatform.defaults();
const headers = getLDHeaders(platform, { sendLDHeaders: true });
expect(headers).toMatchObject({ 'User-Agent': getLDUserAgentString(platform) });
});

it('adds user-agent header with custom name', () => {
const platform = stubPlatform.defaults();
platform.userAgentHeaderName = 'X-Fake-User-Agent';
const headers = getLDHeaders(platform, { sendLDHeaders: true });
expect(headers).toMatchObject({ 'X-Fake-User-Agent': getLDUserAgentString(platform) });
});

it('adds wrapper info if specified, without version', () => {
const platform = stubPlatform.defaults();
const headers = getLDHeaders(platform, { sendLDHeaders: true, wrapperName: 'FakeSDK' });
expect(headers).toMatchObject({
'User-Agent': getLDUserAgentString(platform),
'X-LaunchDarkly-Wrapper': 'FakeSDK',
});
});

it('adds wrapper info if specified, with version', () => {
const platform = stubPlatform.defaults();
const headers = getLDHeaders(platform, { sendLDHeaders: true, wrapperName: 'FakeSDK', wrapperVersion: '9.9' });
expect(headers).toMatchObject({
'User-Agent': getLDUserAgentString(platform),
'X-LaunchDarkly-Wrapper': 'FakeSDK/9.9',
});
});

it('sets the X-LaunchDarkly-Tags header with valid id and version.', () => {
const platform = stubPlatform.defaults();
const headers = getLDHeaders(platform, {
sendLDHeaders: true,
application: {
id: 'test-application',
version: 'test-version',
},
});
expect(headers).toMatchObject({
'User-Agent': getLDUserAgentString(platform),
'x-launchdarkly-tags': 'application-id/test-application application-version/test-version',
});
});

it('sets the X-LaunchDarkly-Tags header with just application id', () => {
const platform = stubPlatform.defaults();
const headers = getLDHeaders(platform, {
sendLDHeaders: true,
application: {
id: 'test-application',
},
});
expect(headers).toMatchObject({
'User-Agent': getLDUserAgentString(platform),
'x-launchdarkly-tags': 'application-id/test-application',
});
});

it('sets the X-LaunchDarkly-Tags header with just application version.', () => {
const platform = stubPlatform.defaults();
const headers = getLDHeaders(platform, {
sendLDHeaders: true,
application: {
version: 'test-version',
},
});
expect(headers).toMatchObject({
'User-Agent': getLDUserAgentString(platform),
'x-launchdarkly-tags': 'application-version/test-version',
});
});
});

describe('transformHeaders', () => {
it('does not modify the headers if the option is not available', () => {
const inputHeaders = { a: '1', b: '2' };
const headers = transformHeaders(inputHeaders, {});
expect(headers).toEqual(inputHeaders);
});

it('modifies the headers if the option has a transform', () => {
const inputHeaders = { c: '3', d: '4' };
const outputHeaders = { c: '9', d: '4', e: '5' };
const headerTransform = input => {
const output = { ...input };
output['c'] = '9';
output['e'] = '5';
return output;
};
const headers = transformHeaders(inputHeaders, { requestHeaderTransform: headerTransform });
expect(headers).toEqual(outputHeaders);
});

it('cannot mutate the input header object', () => {
const inputHeaders = { f: '6' };
const expectedInputHeaders = { f: '6' };
const headerMutate = input => {
input['f'] = '7'; // eslint-disable-line no-param-reassign
return input;
};
transformHeaders(inputHeaders, { requestHeaderTransform: headerMutate });
expect(inputHeaders).toEqual(expectedInputHeaders);
});
});
Loading

0 comments on commit c6ca9d2

Please sign in to comment.