Skip to content

Commit f825cd7

Browse files
authoredJul 18, 2022
Revert "Report result was found or not (#46)" (#49)
This reverts commit 5cd4919.
1 parent 5cd4919 commit f825cd7

12 files changed

+9
-250
lines changed
 

‎README.md

+2-15
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,9 @@ type MonitoredOptions = {
101101
level?: 'info' | 'debug'; //which log level to write (debug is the default)
102102
logAsError?: boolean; //enables to write error log in case the global `logErrorsAsWarnings` is on
103103
logErrorAsInfo?: boolean //enables to write the error as info log
104-
shouldMonitorError: e => boolean // define the conditions of reporting and logging an error, defaults to true
105-
shouldMonitorSuccess: (r: T) => boolean // define the conditions of reporting and logging wether a result was successful or not, defaults to true
104+
shouldMonitorError: e => boolean //determines if error should be monitored and logged, defaults to true
105+
shouldMonitorSuccess: (r: T) => boolean //determines if success result should be monitored and logged, defaults to true
106106
tags?: Record<string, string>; //add more information/labels to metrics
107-
shouldMonitorResultFound?: (r: Awaited<T>) => boolean; // define the conditions of reporting wether a result was found or not, defaults to false
108107
};
109108
```
110109

@@ -144,18 +143,6 @@ const result = monitored(
144143
);
145144
```
146145

147-
#### You can report an empty result by defining a predicate in `shouldMonitorResultFound`:
148-
149-
```ts
150-
const result = monitored(
151-
'functionName',
152-
() => {
153-
return [1, 2, 3];
154-
},
155-
{context: {id: 'some context'}, shouldMonitorResultFound: (result)=>{return result.length > 0}}
156-
);
157-
```
158-
159146
### `flush`
160147

161148
Wait until all current metrics are sent to the server. <br>

‎__tests__/PrometheusPlugin.spec.ts

-82
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,6 @@ const gauge = {
1818
labels: jest.fn().mockImplementation(() => ({set: gaugeSet})),
1919
};
2020

21-
const isResultFoundCallback = (result: Awaited<number[]>): boolean => {
22-
return result.length > 0;
23-
};
24-
2521
jest.mock('prom-client', () => ({
2622
Histogram: jest.fn().mockImplementation(() => histogram),
2723
Counter: jest.fn().mockImplementation(() => counter),
@@ -68,60 +64,6 @@ describe('PrometheusPlugin', () => {
6864
expect(counterInc).toHaveBeenCalledWith(1);
6965
expect(counter.labels).toHaveBeenCalledWith({result: 'success'});
7066
expect(counterInc).toHaveBeenCalledWith(1);
71-
expect(counter.labels).not.toHaveBeenCalledWith({result: 'found'});
72-
expect(counter.labels).not.toHaveBeenCalledWith({result: 'notFound'});
73-
expect(histogram.labels).toHaveBeenCalledWith({result: 'success'});
74-
expect(histogramObserve).toHaveBeenCalledWith(expect.any(Number));
75-
});
76-
77-
it('reports result found on onSuccess', () => {
78-
monitor.monitored('abc', () => [1, 2, 3], {shouldMonitorResultFound: isResultFoundCallback});
79-
80-
expect(Counter).toHaveBeenCalledWith({
81-
name: `abc_count`,
82-
help: `abc_count`,
83-
labelNames: ['result'],
84-
});
85-
86-
expect(Histogram).toHaveBeenCalledWith({
87-
name: `abc_execution_time`,
88-
help: `abc_execution_time`,
89-
buckets: DEFAULT_BUCKETS,
90-
labelNames: ['result'],
91-
});
92-
93-
expect(counter.labels).toHaveBeenCalledWith({result: 'start'});
94-
expect(counterInc).toHaveBeenCalledWith(1);
95-
expect(counter.labels).toHaveBeenCalledWith({result: 'success'});
96-
expect(counterInc).toHaveBeenCalledWith(1);
97-
expect(counter.labels).toHaveBeenCalledWith({result: 'found'});
98-
expect(counterInc).toHaveBeenCalledWith(1);
99-
expect(histogram.labels).toHaveBeenCalledWith({result: 'success'});
100-
expect(histogramObserve).toHaveBeenCalledWith(expect.any(Number));
101-
});
102-
103-
it('reports result not found on onSuccess', () => {
104-
monitor.monitored('abc', () => [], {shouldMonitorResultFound: isResultFoundCallback});
105-
106-
expect(Counter).toHaveBeenCalledWith({
107-
name: `abc_count`,
108-
help: `abc_count`,
109-
labelNames: ['result'],
110-
});
111-
112-
expect(Histogram).toHaveBeenCalledWith({
113-
name: `abc_execution_time`,
114-
help: `abc_execution_time`,
115-
buckets: DEFAULT_BUCKETS,
116-
labelNames: ['result'],
117-
});
118-
119-
expect(counter.labels).toHaveBeenCalledWith({result: 'start'});
120-
expect(counterInc).toHaveBeenCalledWith(1);
121-
expect(counter.labels).toHaveBeenCalledWith({result: 'success'});
122-
expect(counterInc).toHaveBeenCalledWith(1);
123-
expect(counter.labels).toHaveBeenCalledWith({result: 'notFound'});
124-
expect(counterInc).toHaveBeenCalledWith(1);
12567
expect(histogram.labels).toHaveBeenCalledWith({result: 'success'});
12668
expect(histogramObserve).toHaveBeenCalledWith(expect.any(Number));
12769
});
@@ -137,30 +79,6 @@ describe('PrometheusPlugin', () => {
13779
expect(counterInc).toHaveBeenCalledWith(1);
13880
expect(counter.labels).toHaveBeenCalledWith({result: 'failure'});
13981
expect(counterInc).toHaveBeenCalledWith(1);
140-
expect(counter.labels).not.toHaveBeenCalledWith({result: 'found'});
141-
expect(counter.labels).not.toHaveBeenCalledWith({result: 'notFound'});
142-
});
143-
144-
it('not to report result found onFailure', () => {
145-
expect(() =>
146-
monitor.monitored(
147-
'abc',
148-
() => {
149-
if (false) {
150-
return [1, 2];
151-
}
152-
throw new Error('123');
153-
},
154-
{shouldMonitorResultFound: isResultFoundCallback}
155-
)
156-
).toThrow();
157-
158-
expect(counter.labels).toHaveBeenCalledWith({result: 'start'});
159-
expect(counterInc).toHaveBeenCalledWith(1);
160-
expect(counter.labels).toHaveBeenCalledWith({result: 'failure'});
161-
expect(counterInc).toHaveBeenCalledWith(1);
162-
expect(counter.labels).not.toHaveBeenCalledWith({result: 'found'});
163-
expect(counter.labels).not.toHaveBeenCalledWith({result: 'notFound'});
16482
});
16583

16684
it('should call registry', () => {

‎__tests__/StatsdPlugin.spec.ts

+1-52
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,11 @@ import {StatsCb, Tags} from 'hot-shots';
22
import {mocked} from 'jest-mock';
33
import Monitor from '../src/Monitor';
44
import {StatsdPlugin, StatsdPluginOptions} from '../src/plugins/StatsdPlugin';
5-
import {
6-
assertGaugeWasCalled,
7-
assertIncrementWasCalled,
8-
assertIncrementWasNotCalled,
9-
assertTimingWasCalled,
10-
} from './utils';
5+
import {assertGaugeWasCalled, assertIncrementWasCalled, assertTimingWasCalled} from './utils';
116
import {MockStatsdPlugin} from './__mocks__/plugins/StatsdPlugin';
127

138
jest.mock('hot-shots');
149

15-
const isResultFoundCallback = (result: Awaited<number[]>): boolean => {
16-
return result.length > 0;
17-
};
18-
1910
beforeEach(() => {
2011
jest.resetAllMocks();
2112
});
@@ -35,26 +26,6 @@ describe('StatsdPlugin', () => {
3526
monitor.monitored('abc', () => 123);
3627

3728
assertIncrementWasCalled(plugin, 'abc.start');
38-
assertIncrementWasNotCalled(plugin, 'abc.result.found');
39-
assertIncrementWasNotCalled(plugin, 'abc.result.notFound');
40-
assertGaugeWasCalled(plugin, 'abc.ExecutionTime');
41-
assertTimingWasCalled(plugin, 'abc.ExecutionTime');
42-
});
43-
44-
test('onSuccess report result is found', () => {
45-
monitor.monitored('abc', () => [1, 2], {shouldMonitorResultFound: isResultFoundCallback});
46-
47-
assertIncrementWasCalled(plugin, 'abc.start');
48-
assertIncrementWasCalled(plugin, 'abc.result.found');
49-
assertGaugeWasCalled(plugin, 'abc.ExecutionTime');
50-
assertTimingWasCalled(plugin, 'abc.ExecutionTime');
51-
});
52-
53-
test('onSuccess report result is not found', () => {
54-
monitor.monitored('abc', () => [], {shouldMonitorResultFound: isResultFoundCallback});
55-
56-
assertIncrementWasCalled(plugin, 'abc.start');
57-
assertIncrementWasCalled(plugin, 'abc.result.notFound');
5829
assertGaugeWasCalled(plugin, 'abc.ExecutionTime');
5930
assertTimingWasCalled(plugin, 'abc.ExecutionTime');
6031
});
@@ -75,28 +46,6 @@ describe('StatsdPlugin', () => {
7546

7647
assertIncrementWasCalled(plugin, 'abc.start');
7748
assertIncrementWasCalled(plugin, 'abc.error');
78-
assertIncrementWasNotCalled(plugin, 'abc.result.found');
79-
assertIncrementWasNotCalled(plugin, 'abc.result.notFound');
80-
});
81-
82-
test('onFailure dont report result is found', () => {
83-
expect(() => {
84-
monitor.monitored(
85-
'abc',
86-
() => {
87-
if (false) {
88-
return [1, 2];
89-
}
90-
throw new Error('123');
91-
},
92-
{shouldMonitorResultFound: isResultFoundCallback}
93-
);
94-
}).toThrow(new Error('123'));
95-
96-
assertIncrementWasCalled(plugin, 'abc.start');
97-
assertIncrementWasCalled(plugin, 'abc.error');
98-
assertIncrementWasNotCalled(plugin, 'abc.result.found');
99-
assertIncrementWasNotCalled(plugin, 'abc.result.notFound');
10049
});
10150
});
10251

‎__tests__/__mocks__/plugins/StatsdPlugin.ts

-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ export class MockStatsdPlugin {
77
onStart = StatsdPlugin.prototype.onStart;
88
onSuccess = StatsdPlugin.prototype.onSuccess;
99
onFailure = StatsdPlugin.prototype.onFailure;
10-
reportResultIsFound = StatsdPlugin.prototype.reportResultIsFound;
1110
increment = jest.fn();
1211
gauge = jest.fn();
1312
timing = jest.fn();

‎__tests__/monitor.spec.ts

-46
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ const mockPlugin: jest.Mocked<MonitoredPlugin> = {
77
onStart: jest.fn(),
88
onSuccess: jest.fn(),
99
onFailure: jest.fn(),
10-
reportResultIsFound: jest.fn(),
1110
flush: jest.fn(),
1211
gauge: jest.fn(),
1312
increment: jest.fn(),
@@ -189,50 +188,5 @@ describe('Monitor', () => {
189188
expect(() => monitor.monitored('test', doThrow(new Error()), {shouldMonitorError})).toThrow();
190189
expect(mockPlugin.onFailure).toHaveBeenCalled();
191190
});
192-
193-
describe('reportIsResultFound for %p', () => {
194-
const callBack = (result: Awaited<number[]>): boolean => {
195-
return result.length > 0;
196-
};
197-
198-
test('async success', async () => {
199-
const returnedValue = [1, 2];
200-
const asyncMockFunc = jest.fn().mockResolvedValue(returnedValue);
201-
202-
await monitor.monitored('monitorFound', asyncMockFunc, {shouldMonitorResultFound: callBack});
203-
expect(mockPlugin.reportResultIsFound).toHaveBeenCalledTimes(1);
204-
});
205-
206-
test('async failed', async () => {
207-
const mockError = new Error('error');
208-
const asyncFailMockFunc = async () => {
209-
return Promise.reject(mockError);
210-
};
211-
212-
await expect(
213-
monitor.monitored('monitorFound', asyncFailMockFunc, {shouldMonitorResultFound: callBack})
214-
).rejects.toBe(mockError);
215-
expect(mockPlugin.reportResultIsFound).toHaveBeenCalledTimes(0);
216-
});
217-
218-
test('sync success', () => {
219-
const returnedValue = [1, 2];
220-
const syncMockFunc = jest.fn().mockReturnValue(returnedValue);
221-
222-
monitor.monitored('monitorFound', syncMockFunc, {shouldMonitorResultFound: callBack});
223-
expect(mockPlugin.reportResultIsFound).toHaveBeenCalledTimes(1);
224-
});
225-
226-
test('sync failed', () => {
227-
const mockError = new Error('error');
228-
const syncFailMockFunc = () => {
229-
throw mockError;
230-
};
231-
expect(() =>
232-
monitor.monitored('monitorFound', syncFailMockFunc, {shouldMonitorResultFound: callBack})
233-
).toThrow(mockError);
234-
expect(mockPlugin.reportResultIsFound).toHaveBeenCalledTimes(0);
235-
});
236-
});
237191
});
238192
});

‎package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "monitored",
3-
"version": "0.1.3",
3+
"version": "0.1.2",
44
"description": "A utility for monitoring services",
55
"main": "dist/index.js",
66
"types": "dist/index.d.ts",

‎src/Monitor.ts

+1-17
Original file line numberDiff line numberDiff line change
@@ -58,29 +58,13 @@ class Monitor {
5858
startTime: number,
5959
options: MonitoredOptions<T>
6060
): Awaited<T> {
61-
const {
62-
shouldMonitorSuccess,
63-
logResult,
64-
level = 'debug',
65-
context,
66-
parseResult,
67-
shouldMonitorResultFound,
68-
} = options;
61+
const {shouldMonitorSuccess, logResult, level = 'debug', context, parseResult} = options;
6962
const executionTime = Date.now() - startTime;
7063

7164
if (shouldMonitorSuccess?.(result) ?? true) {
7265
this.plugins.onSuccess({scope, executionTime, options});
7366
}
7467

75-
if (shouldMonitorResultFound) {
76-
try {
77-
const isFound = shouldMonitorResultFound(result);
78-
this.plugins.reportResultIsFound({scope, options}, isFound);
79-
} catch {
80-
this.monitoredLogger('debug', 'isResultFound callback failed', {extra: {context}});
81-
}
82-
}
83-
8468
if (!this.config.disableSuccessLogs) {
8569
this.monitoredLogger(level, `${scope}.success`, {
8670
extra: {

‎src/plugins/PluginsWrapper.ts

+1-12
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,4 @@
1-
import {
2-
EventOptions,
3-
InitializationOptions,
4-
MonitoredPlugin,
5-
OnFailureOptions,
6-
OnStartOptions,
7-
OnSuccessOptions,
8-
} from './types';
1+
import {InitializationOptions, MonitoredPlugin, OnFailureOptions, OnStartOptions, OnSuccessOptions} from './types';
92

103
export class PluginsWrapper implements Omit<MonitoredPlugin, 'initialize'> {
114
constructor(private readonly plugins: MonitoredPlugin[], opts: InitializationOptions) {
@@ -24,10 +17,6 @@ export class PluginsWrapper implements Omit<MonitoredPlugin, 'initialize'> {
2417
this.plugins.forEach(p => p.onFailure(opts));
2518
}
2619

27-
reportResultIsFound(opts: EventOptions, isFound: boolean): void {
28-
this.plugins.forEach(p => p.reportResultIsFound(opts, isFound));
29-
}
30-
3120
async increment(name: string, value?: number, tags?: Record<string, string>): Promise<void> {
3221
await Promise.all(this.plugins.map(p => p.increment(name, value, tags)));
3322
}

‎src/plugins/PrometheusPlugin.ts

+1-7
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {Counter, Histogram, register as registry, Gauge} from 'prom-client';
2-
import {EventOptions, MonitoredPlugin, OnFailureOptions, OnStartOptions, OnSuccessOptions} from './types';
2+
import {MonitoredPlugin, OnFailureOptions, OnStartOptions, OnSuccessOptions} from './types';
33

44
export interface PrometheusPluginOptions {
55
histogramBuckets?: number[];
@@ -31,12 +31,6 @@ export class PrometheusPlugin implements MonitoredPlugin {
3131
this.timing(scope, executionTime, labels);
3232
}
3333

34-
reportResultIsFound({scope, options}: EventOptions, isFound: boolean): void {
35-
const isFoundLabel = isFound ? 'found' : 'notFound';
36-
const labels = {result: isFoundLabel, ...options?.tags};
37-
this.increment(scope, 1, labels);
38-
}
39-
4034
private getMetrics(scope: string) {
4135
if (!this.histograms[scope]) {
4236
this.histograms[scope] = new Histogram({

‎src/plugins/StatsdPlugin.ts

+2-14
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,7 @@ import {ClientOptions, StatsD, Tags} from 'hot-shots';
22
import {promisify} from 'util';
33
import {timeoutPromise} from '../utils';
44
import {Logger} from '../Logger';
5-
import {
6-
EventOptions,
7-
InitializationOptions,
8-
MonitoredPlugin,
9-
OnFailureOptions,
10-
OnStartOptions,
11-
OnSuccessOptions,
12-
} from './types';
5+
import {InitializationOptions, MonitoredPlugin, OnFailureOptions, OnStartOptions, OnSuccessOptions} from './types';
136

147
const noop = () => {};
158

@@ -72,11 +65,6 @@ export class StatsdPlugin implements MonitoredPlugin {
7265
this.increment(`${scope}.error`, 1, options?.tags);
7366
}
7467

75-
reportResultIsFound({scope, options}: EventOptions, isFound: boolean): void {
76-
const isFoundLabel = isFound ? 'found' : 'notFound';
77-
this.increment(`${scope}.result.${isFoundLabel}`, 1, options?.tags);
78-
}
79-
8068
get statsd() {
8169
return this.client;
8270
}
@@ -106,7 +94,7 @@ export class StatsdPlugin implements MonitoredPlugin {
10694
}
10795

10896
async flush(timeout: number = 2000) {
109-
const remainingPromises = Object.values(this.pendingPromises).map(p => p.catch(noop));
97+
const remainingPromises = Object.values(this.pendingPromises).map((p) => p.catch(noop));
11098
if (!remainingPromises.length) {
11199
return true;
112100
}

0 commit comments

Comments
 (0)