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

feat(tracing): auto flush BatchSpanProcessor on browser #2243

Merged
merged 13 commits into from Jun 16, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/opentelemetry-tracing/karma.conf.js
Expand Up @@ -19,6 +19,8 @@ const karmaBaseConfig = require('../../karma.base');

module.exports = (config) => {
config.set(Object.assign({}, karmaBaseConfig, {
webpack: karmaWebpackConfig
webpack: karmaWebpackConfig,
files: ['test/browser/index-webpack.ts'],
preprocessors: { 'test/browser/index-webpack.ts': ['webpack'] }
}))
};
Expand Up @@ -37,7 +37,7 @@ import { SDKRegistrationConfig, TracerConfig } from './types';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const merge = require('lodash.merge');
import { SpanExporter } from './export/SpanExporter';
import { BatchSpanProcessor } from './export/BatchSpanProcessor';
import { BatchSpanProcessor } from './platform';

export type PROPAGATOR_FACTORY = () => TextMapPropagator;
export type EXPORTER_FACTORY = () => SpanExporter;
Expand Down
Expand Up @@ -32,7 +32,7 @@ import { SpanExporter } from './SpanExporter';
* Implementation of the {@link SpanProcessor} that batches spans exported by
* the SDK then pushes them to the exporter pipeline.
*/
export class BatchSpanProcessor implements SpanProcessor {
export abstract class BatchSpanProcessorBase implements SpanProcessor {
private readonly _maxExportBatchSize: number;
private readonly _maxQueueSize: number;
private readonly _scheduledDelayMillis: number;
Expand Down Expand Up @@ -61,6 +61,8 @@ export class BatchSpanProcessor implements SpanProcessor {
typeof config?.exportTimeoutMillis === 'number'
? config?.exportTimeoutMillis
: env.OTEL_BSP_EXPORT_TIMEOUT;

this.onInit();
}

forceFlush(): Promise<void> {
Expand All @@ -87,6 +89,9 @@ export class BatchSpanProcessor implements SpanProcessor {
this._isShutdown = true;
this._shuttingDownPromise = new Promise((resolve, reject) => {
Promise.resolve()
.then(() => {
return this.onShutdown();
})
.then(() => {
return this._flushAll();
})
Expand Down Expand Up @@ -190,4 +195,7 @@ export class BatchSpanProcessor implements SpanProcessor {
this._timer = undefined;
}
}

abstract onInit(): void;
abstract onShutdown(): void;
}
2 changes: 1 addition & 1 deletion packages/opentelemetry-tracing/src/index.ts
Expand Up @@ -16,8 +16,8 @@

export * from './Tracer';
export * from './BasicTracerProvider';
export * from './platform';
export * from './export/ConsoleSpanExporter';
export * from './export/BatchSpanProcessor';
export * from './export/InMemorySpanExporter';
export * from './export/ReadableSpan';
export * from './export/SimpleSpanProcessor';
Expand Down
@@ -0,0 +1,34 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';

export class BatchSpanProcessor extends BatchSpanProcessorBase {
private _onVisibilityChange(): void {
if (document.visibilityState === 'hidden') {
void this.forceFlush();
}
}

onInit(): void {
kkruk-sumo marked this conversation as resolved.
Show resolved Hide resolved
this._onVisibilityChange = this._onVisibilityChange.bind(this);
document.addEventListener('visibilitychange', this._onVisibilityChange);
}

onShutdown(): void {
document.removeEventListener('visibilitychange', this._onVisibilityChange);
}
}
17 changes: 17 additions & 0 deletions packages/opentelemetry-tracing/src/platform/browser/index.ts
@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export * from './export/BatchSpanProcessor';
17 changes: 17 additions & 0 deletions packages/opentelemetry-tracing/src/platform/index.ts
@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export * from './node';
@@ -0,0 +1,23 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';

export class BatchSpanProcessor extends BatchSpanProcessorBase {
onInit(): void {}

onShutdown(): void {}
}
17 changes: 17 additions & 0 deletions packages/opentelemetry-tracing/src/platform/node/index.ts
@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export * from './export/BatchSpanProcessor';
@@ -0,0 +1,62 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as assert from 'assert';
import * as sinon from 'sinon';
import { BatchSpanProcessor } from '../../../src';
import { TestTracingSpanExporter } from '../../common/export/TestTracingSpanExporter';

describe('BatchSpanProcessor - web', () => {
let visibilityState: VisibilityState = 'visible';
let processor: BatchSpanProcessor;
let forceFlushSpy: sinon.SinonStub;
let visibilityChangeEvent: Event;

beforeEach(() => {
sinon.replaceGetter(document, 'visibilityState', () => visibilityState);
visibilityState = 'visible';
const exporter = new TestTracingSpanExporter();
processor = new BatchSpanProcessor(exporter, {});
forceFlushSpy = sinon.stub(processor, 'forceFlush');
visibilityChangeEvent = new Event('visibilitychange');
});

afterEach(() => {
processor.onShutdown();
sinon.restore();
});

it('forces flush when page becomes hidden', () => {
obecny marked this conversation as resolved.
Show resolved Hide resolved
assert.strictEqual(forceFlushSpy.callCount, 0);
visibilityState = 'hidden';
document.dispatchEvent(visibilityChangeEvent);
assert.strictEqual(forceFlushSpy.callCount, 1);
});

it("doesn't force flush when page becomes visible", () => {
assert.strictEqual(forceFlushSpy.callCount, 0);
document.dispatchEvent(visibilityChangeEvent);
assert.strictEqual(forceFlushSpy.callCount, 0);
});

it("doesn't force flush when page becomes hidden after shutting down", async () => {
assert.strictEqual(forceFlushSpy.callCount, 0);
await processor.shutdown();
visibilityState = 'hidden';
document.dispatchEvent(visibilityChangeEvent);
assert.strictEqual(forceFlushSpy.callCount, 0);
});
});
Expand Up @@ -13,8 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const testsContext = require.context('.', true, /test$/);
const testsContext = require.context('../browser', true, /test$/);
testsContext.keys().forEach(testsContext);

const testsContextCommon = require.context('../common', true, /test$/);
testsContextCommon.keys().forEach(testsContextCommon);

const srcContext = require.context('.', true, /src$/);
srcContext.keys().forEach(srcContext);
Expand Up @@ -43,7 +43,7 @@ import {
InMemorySpanExporter,
SpanExporter,
BatchSpanProcessor,
} from '../src';
} from '../../src';

describe('BasicTracerProvider', () => {
let removeEvent: Function | undefined;
Expand Down
Expand Up @@ -22,12 +22,12 @@ import {
SimpleSpanProcessor,
Span,
SpanProcessor,
} from '../src';
} from '../../src';
import {
setGlobalErrorHandler,
loggingErrorHandler,
} from '@opentelemetry/core';
import { MultiSpanProcessor } from '../src/MultiSpanProcessor';
import { MultiSpanProcessor } from '../../src/MultiSpanProcessor';

class TestProcessor implements SpanProcessor {
spans: Span[] = [];
Expand Down
Expand Up @@ -30,7 +30,7 @@ import {
} from '@opentelemetry/core';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import * as assert from 'assert';
import { BasicTracerProvider, Span, SpanProcessor } from '../src';
import { BasicTracerProvider, Span, SpanProcessor } from '../../src';

const performanceTimeOrigin = hrTime();

Expand Down
Expand Up @@ -30,7 +30,7 @@ import {
suppressTracing,
} from '@opentelemetry/core';
import * as assert from 'assert';
import { BasicTracerProvider, Span, Tracer } from '../src';
import { BasicTracerProvider, Span, Tracer } from '../../src';

describe('Tracer', () => {
const tracerProvider = new BasicTracerProvider();
Expand Down
Expand Up @@ -20,7 +20,7 @@ import {
TraceIdRatioBasedSampler,
} from '@opentelemetry/core';
import * as assert from 'assert';
import { buildSamplerFromEnv } from '../src/config';
import { buildSamplerFromEnv } from '../../src/config';

describe('config', () => {
const envSource = (typeof window !== 'undefined'
Expand Down
Expand Up @@ -23,15 +23,11 @@ import {
} from '@opentelemetry/core';
import * as assert from 'assert';
import * as sinon from 'sinon';
import {
BasicTracerProvider,
BatchSpanProcessor,
InMemorySpanExporter,
Span,
} from '../../src';
import { BasicTracerProvider, InMemorySpanExporter, Span } from '../../../src';
import { context } from '@opentelemetry/api';
import { TestTracingSpanExporter } from './TestTracingSpanExporter';
import { TestStackContextManager } from './TestStackContextManager';
import { BatchSpanProcessorBase } from '../../../src/export/BatchSpanProcessorBase';

function createSampledSpan(spanName: string): Span {
const tracer = new BasicTracerProvider({
Expand All @@ -42,16 +38,25 @@ function createSampledSpan(spanName: string): Span {
return span as Span;
}

describe('BatchSpanProcessor', () => {
class BatchSpanProcessor extends BatchSpanProcessorBase {
onInit() {}
onShutdown() {}
}

describe('BatchSpanProcessorBase', () => {
const name = 'span-name';
const defaultBufferConfig = {
maxExportBatchSize: 5,
scheduledDelayMillis: 2500,
};
let exporter: InMemorySpanExporter;
let onInitSpy: any;

beforeEach(() => {
exporter = new InMemorySpanExporter();
onInitSpy = sinon.stub(BatchSpanProcessor.prototype, 'onInit');
});

afterEach(() => {
exporter.reset();
sinon.restore();
Expand All @@ -76,6 +81,11 @@ describe('BatchSpanProcessor', () => {
processor.shutdown();
});

it('should call onInit', () => {
new BatchSpanProcessor(exporter, {});
assert.strictEqual(onInitSpy.callCount, 1);
});

it('should read defaults from environment', () => {
const bspConfig = {
OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 256,
Expand Down Expand Up @@ -104,6 +114,14 @@ describe('BatchSpanProcessor', () => {
});

describe('.onStart/.onEnd/.shutdown', () => {
it('should call onShutdown', async () => {
const processor = new BatchSpanProcessor(exporter, defaultBufferConfig);
const onShutdownSpy = sinon.stub(processor, 'onShutdown');
assert.strictEqual(onShutdownSpy.callCount, 0);
await processor.shutdown();
assert.strictEqual(onShutdownSpy.callCount, 1);
});

it('should do nothing after processor is shutdown', async () => {
const processor = new BatchSpanProcessor(exporter, defaultBufferConfig);
const spy: sinon.SinonSpy = sinon.spy(exporter, 'export') as any;
Expand Down
Expand Up @@ -21,7 +21,7 @@ import {
BasicTracerProvider,
ConsoleSpanExporter,
SimpleSpanProcessor,
} from '../../src';
} from '../../../src';

/* eslint-disable no-console */
describe('ConsoleSpanExporter', () => {
Expand Down
Expand Up @@ -19,7 +19,7 @@ import {
InMemorySpanExporter,
SimpleSpanProcessor,
BasicTracerProvider,
} from '../../src';
} from '../../../src';
import { context, trace } from '@opentelemetry/api';
import { ExportResult, ExportResultCode } from '@opentelemetry/core';

Expand Down