Skip to content
This repository has been archived by the owner on Oct 3, 2023. It is now read-only.

Commit

Permalink
[Core] Enforce strictNullChecks (#453)
Browse files Browse the repository at this point in the history
* Enforce null check on [core] package

* fix review comments

1. Assign default value to parentSpanId and name.
2. Assign default value({}) to activeTraceParams.
3. Add traceState back for no-record-span-base

* Add NoopLogger class

* Use map and filter instread of loop + added TODO

* Remove  and fix comment

* Change TraceState = string|undefined -> TraceState = string

* Fix build
  • Loading branch information
mayurkale22 committed Mar 31, 2019
1 parent 9f4a627 commit 469d15a
Show file tree
Hide file tree
Showing 48 changed files with 406 additions and 650 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ All notable changes to this project will be documented in this file.
- Add support for recording Exemplars.
- Add `TagMetadata` that defines the properties associated with a `Tag`.
- Add HTTP text format serializer to Tag propagation component.
- Enforce `--strictNullChecks` and `--noUnusedLocals` Compiler Options on [opencensus-core] package.

## 0.0.9 - 2019-02-12
- Add Metrics API.
Expand Down
4 changes: 2 additions & 2 deletions packages/opencensus-core/src/common/console-logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const logDriver = require('log-driver');
export class ConsoleLogger implements types.Logger {
private logger: typeof logDriver;
static LEVELS = ['silent', 'error', 'warn', 'info', 'debug'];
level: string;
level?: string;

/**
* Constructs a new ConsoleLogger instance
Expand All @@ -45,7 +45,7 @@ export class ConsoleLogger implements types.Logger {
} else {
opt = options || {};
}
this.level = opt.level;
if (opt.level) this.level = opt.level;
this.logger =
logDriver({levels: ConsoleLogger.LEVELS, level: opt.level || 'silent'});
}
Expand Down
31 changes: 31 additions & 0 deletions packages/opencensus-core/src/common/noop-logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* Copyright 2019, OpenCensus 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
*
* http://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 {Logger} from './types';

/** No-op implementation of Logger */
class NoopLogger implements Logger {
// tslint:disable-next-line:no-any
debug(message: string, ...args: any[]) {}
// tslint:disable-next-line:no-any
error(...args: any[]) {}
// tslint:disable-next-line:no-any
warn(...args: any[]) {}
// tslint:disable-next-line:no-any
info(...args: any[]) {}
}

export const noopLogger = new NoopLogger();
4 changes: 2 additions & 2 deletions packages/opencensus-core/src/exporters/console-exporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import * as types from './types';

/** Do not send span data */
export class NoopExporter implements types.Exporter {
logger: loggerTypes.Logger;
logger?: loggerTypes.Logger;
onStartSpan(root: modelTypes.RootSpan) {}
onEndSpan(root: modelTypes.RootSpan) {}
publish(rootSpans: modelTypes.RootSpan[]) {
Expand All @@ -36,7 +36,7 @@ export class NoopExporter implements types.Exporter {
export class ConsoleExporter implements types.Exporter {
/** Buffer object to store the spans. */
// @ts-ignore
private logger: loggerTypes.Logger;
private logger?: loggerTypes.Logger;
private buffer: ExporterBuffer;

/**
Expand Down
10 changes: 8 additions & 2 deletions packages/opencensus-core/src/exporters/exporter-buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import * as configTypes from '../trace/config/types';
import * as modelTypes from '../trace/model/types';
import * as types from './types';

const DEFAULT_BUFFER_SIZE = 100;
const DEFAULT_BUFFER_TIMEOUT = 20000;

/** Controls the sending of traces to exporters. */
export class ExporterBuffer {
Expand All @@ -46,8 +48,12 @@ export class ExporterBuffer {
constructor(exporter: types.Exporter, config: configTypes.BufferConfig) {
this.exporter = exporter;
this.logger = config.logger || logger.logger();
this.bufferSize = config.bufferSize;
this.bufferTimeout = config.bufferTimeout;
this.bufferSize = isNaN(Number(config.bufferSize)) ?
DEFAULT_BUFFER_SIZE :
Number(config.bufferSize);
this.bufferTimeout = isNaN(Number(config.bufferTimeout)) ?
DEFAULT_BUFFER_TIMEOUT :
Number(config.bufferTimeout);
return this;
}

Expand Down
9 changes: 4 additions & 5 deletions packages/opencensus-core/src/internal/clock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class Clock {
/** The time in high resolution in a [seconds, nanoseconds]. */
private hrtimeLocal: [number, number];
/** The duration between start and end of the clock. */
private diff: [number, number] = null;
private diff: [number, number] = [0, 0];

/** Constructs a new SamplerImpl instance. */
constructor() {
Expand All @@ -46,7 +46,7 @@ export class Clock {
/** Gets the duration of the clock. */
get duration(): number {
if (!this.endedLocal) {
return null;
return 0;
}
const ns = this.diff[0] * 1e9 + this.diff[1];
return ns / 1e6;
Expand All @@ -63,11 +63,10 @@ export class Clock {
* @returns A Date object with the current duration.
*/
get endTime(): Date {
let result: Date = null;
if (this.ended) {
result = new Date(this.startTime.getTime() + this.duration);
return new Date(this.startTime.getTime() + this.duration);
}
return result;
return new Date();
}

/** Indicates if the clock was ended. */
Expand Down
4 changes: 2 additions & 2 deletions packages/opencensus-core/src/metrics/gauges/derived-gauge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export class DerivedGauge implements types.Meter {
private metricDescriptor: MetricDescriptor;
private labelKeysLength: number;
private registeredPoints: Map<string, GaugeEntry> = new Map();
private extractor: ValueExtractor;
private extractor?: ValueExtractor;

private static readonly LABEL_VALUE = 'labelValue';
private static readonly LABEL_VALUES = 'labelValues';
Expand Down Expand Up @@ -201,7 +201,7 @@ export class DerivedGauge implements types.Meter {
*
* @returns {Metric} The Metric.
*/
getMetric(): Metric {
getMetric(): Metric|null {
if (this.registeredPoints.size === 0) {
return null;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/opencensus-core/src/metrics/gauges/gauge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export class Gauge implements types.Meter {
const hash = hashLabelValues(labelValues);
// return if the specified labelValues is already associated with the point.
if (this.registeredPoints.has(hash)) {
return this.registeredPoints.get(hash);
return this.registeredPoints.get(hash)!;
}
if (this.labelKeysLength !== labelValues.length) {
throw new Error(Gauge.ERROR_MESSAGE_INVALID_SIZE);
Expand All @@ -126,7 +126,7 @@ export class Gauge implements types.Meter {
*
* @returns {Metric} The Metric.
*/
getMetric(): Metric {
getMetric(): Metric|null {
if (this.registeredPoints.size === 0) {
return null;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/opencensus-core/src/metrics/gauges/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export interface Meter {
*
* @returns {Metric} The Metric.
*/
getMetric(): Metric;
getMetric(): Metric|null;
}

export interface Point {
Expand Down
5 changes: 3 additions & 2 deletions packages/opencensus-core/src/metrics/metric-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,8 @@ class MetricProducerForRegistry extends BaseMetricProducer {
* @returns {Metric[]} The list of metrics.
*/
getMetrics(): Metric[] {
return Array.from(
this.registeredMetrics, ([_, meter]) => meter.getMetric());
return Array.from(this.registeredMetrics.values())
.map(meter => meter.getMetric())
.filter(meter => !!meter) as Metric[];
}
}
65 changes: 32 additions & 33 deletions packages/opencensus-core/src/resource/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,10 @@ export class CoreResource {
* @returns {Resource} The resource.
*/
static mergeResources(resources: Resource[]): Resource {
let currentResource: Resource;
for (const resource of resources) {
currentResource = this.merge(currentResource, resource);
if (resources.length === 0) return {type: 'global', labels: {}};
let currentResource = resources[0];
for (let i = 1; i < resources.length; i++) {
currentResource = this.merge(currentResource, resources[i]);
}
return currentResource;
}
Expand All @@ -81,14 +82,12 @@ export class CoreResource {
* @param {string} rawEnvType The resource type.
* @returns {string} The sanitized resource type.
*/
private static parseResourceType(rawEnvType: string): string {
if (rawEnvType) {
if (!CoreResource.isValidAndNotEmpty(rawEnvType)) {
throw new Error(`Type ${CoreResource.ERROR_MESSAGE_INVALID_CHARS}`);
}
return rawEnvType.trim();
private static parseResourceType(rawEnvType?: string): string|null {
if (!rawEnvType) return null;
if (!CoreResource.isValidAndNotEmpty(rawEnvType)) {
throw new Error(`Type ${CoreResource.ERROR_MESSAGE_INVALID_CHARS}`);
}
return null;
return rawEnvType.trim();
}

/**
Expand All @@ -103,30 +102,30 @@ export class CoreResource {
* of key/value pairs.
* @returns {Labels} The sanitized resource labels.
*/
private static parseResourceLabels(rawEnvLabels: string): Labels {
private static parseResourceLabels(rawEnvLabels?: string): Labels {
if (!rawEnvLabels) return {};

const labels: Labels = {};
if (rawEnvLabels) {
const rawLabels: string[] = rawEnvLabels.split(this.COMMA_SEPARATOR, -1);
for (const rawLabel of rawLabels) {
const keyValuePair: string[] =
rawLabel.split(this.LABEL_KEY_VALUE_SPLITTER, -1);
if (keyValuePair.length !== 2) {
continue;
}
let [key, value] = keyValuePair;
// Leading and trailing whitespaces are trimmed.
key = key.trim();
value = value.trim().split('^"|"$').join('');
if (!CoreResource.isValidAndNotEmpty(key)) {
throw new Error(
`Label key ${CoreResource.ERROR_MESSAGE_INVALID_CHARS}`);
}
if (!CoreResource.isValid(value)) {
throw new Error(
`Label value ${CoreResource.ERROR_MESSAGE_INVALID_VALUE}`);
}
labels[key] = value;
const rawLabels: string[] = rawEnvLabels.split(this.COMMA_SEPARATOR, -1);
for (const rawLabel of rawLabels) {
const keyValuePair: string[] =
rawLabel.split(this.LABEL_KEY_VALUE_SPLITTER, -1);
if (keyValuePair.length !== 2) {
continue;
}
let [key, value] = keyValuePair;
// Leading and trailing whitespaces are trimmed.
key = key.trim();
value = value.trim().split('^"|"$').join('');
if (!CoreResource.isValidAndNotEmpty(key)) {
throw new Error(
`Label key ${CoreResource.ERROR_MESSAGE_INVALID_CHARS}`);
}
if (!CoreResource.isValid(value)) {
throw new Error(
`Label value ${CoreResource.ERROR_MESSAGE_INVALID_VALUE}`);
}
labels[key] = value;
}
return labels;
}
Expand Down Expand Up @@ -173,7 +172,7 @@ export class CoreResource {
* @returns {boolean} Whether the String is valid and not empty.
*/
private static isValidAndNotEmpty(name: string): boolean {
return name && name.length > 0 && CoreResource.isValid(name);
return name.length > 0 && CoreResource.isValid(name);
}

/** TEST_ONLY */
Expand Down
2 changes: 1 addition & 1 deletion packages/opencensus-core/src/resource/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export interface Resource {
/**
* An optional string which describes a well-known type of resource.
*/
readonly type: string;
readonly type: string|null;

/**
* A dictionary of labels with string keys and values that provide information
Expand Down
24 changes: 13 additions & 11 deletions packages/opencensus-core/src/stats/bucket-boundaries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,18 @@ export class BucketBoundaries {
private dropNegativeBucketBounds(bucketBoundaries: number[]): Bucket[] {
let negative = 0;
if (!bucketBoundaries) return [];
const result = bucketBoundaries.reduce((accumulator, boundary, index) => {
if (boundary > 0) {
const nextBoundary = bucketBoundaries[index + 1];
this.validateBoundary(boundary, nextBoundary);
accumulator.push(boundary);
} else {
negative++;
}
return accumulator;
}, []);
const result = bucketBoundaries.reduce(
(accumulator: number[], boundary: number, index: number) => {
if (boundary > 0) {
const nextBoundary = bucketBoundaries[index + 1];
this.validateBoundary(boundary, nextBoundary);
accumulator.push(boundary);
} else {
negative++;
}
return accumulator;
},
[]);
if (negative) {
this.logger.warn(`Dropping ${
negative} negative bucket boundaries, the values must be strictly > 0.`);
Expand Down Expand Up @@ -95,4 +97,4 @@ export class BucketBoundaries {
}
}
}
}
}
2 changes: 1 addition & 1 deletion packages/opencensus-core/src/stats/metric-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export class MetricUtils {
* @param tagValues
* @returns {LabelValue[]} List of label values
*/
static tagValuesToLabelValues(tagValues: TagValue[]): LabelValue[] {
static tagValuesToLabelValues(tagValues: Array<TagValue|null>): LabelValue[] {
return tagValues.map(
(tagValue) => ({value: tagValue ? tagValue.value : null}));
}
Expand Down
13 changes: 9 additions & 4 deletions packages/opencensus-core/src/stats/recorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import {TagKey, TagValue} from '../tags/types';
import {AggregationData, AggregationType, CountData, DistributionData, LastValueData, Measurement, MeasureType, SumData} from './types';

const UNKNOWN_TAG_VALUE: TagValue = null;
const UNKNOWN_TAG_VALUE: TagValue|null = null;

export class Recorder {
static addMeasurement(
Expand Down Expand Up @@ -45,7 +45,7 @@ export class Recorder {

/** Gets the tag values from tags and columns */
static getTagValues(tags: Map<TagKey, TagValue>, columns: TagKey[]):
TagValue[] {
Array<TagValue|null> {
return columns.map(
(tagKey) =>
(tags.get(tagKey) ||
Expand All @@ -63,7 +63,11 @@ export class Recorder {
if (bucketIndex < 0) {
bucketIndex = distributionData.buckets.length;
}
distributionData.bucketCounts[bucketIndex] += 1;

if (distributionData.bucketCounts &&
distributionData.bucketCounts.length > bucketIndex) {
distributionData.bucketCounts[bucketIndex] += 1;
}

if (distributionData.count === 1) {
distributionData.mean = value;
Expand All @@ -82,7 +86,8 @@ export class Recorder {

// No implicit recording for exemplars - if there are no attachments
// (contextual information), don't record exemplars.
if (attachments) {
if (attachments && distributionData.exemplars &&
distributionData.exemplars.length > bucketIndex) {
distributionData.exemplars[bucketIndex] = {
value,
timestamp: distributionData.timestamp,
Expand Down
4 changes: 2 additions & 2 deletions packages/opencensus-core/src/stats/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ export interface View {
/**
* The end time for this view - represents the last time a value was recorded
*/
endTime: number;
endTime?: number;
/** true if the view was registered */
registered: boolean;
/**
Expand Down Expand Up @@ -233,7 +233,7 @@ export interface AggregationMetadata {
/** The aggregation type of the aggregation data */
readonly type: AggregationType;
/** The tagValues that this AggregationData collects and aggregates */
readonly tagValues: TagValue[];
readonly tagValues: Array<TagValue|null>;
/** The latest timestamp a new data point was recorded */
timestamp: number;
}
Expand Down
Loading

0 comments on commit 469d15a

Please sign in to comment.