File size: 1,871 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { ReportImpl } from './report';
import { send } from './transports/logstash';
import type { Collector, Report, ReportData, ReportPayload } from './types';

const inFlightReporters: Map< string, Promise< Report > > = new Map();

/**
 * Starts a new report
 * @param id id of the report, must be passed to `stop()` to stop it
 * @param obj Options
 * @param obj.fullPageLoad `true` if the report should start measuring from the load of the page, `false` to start measuring from now.
 * @param obj.collectors list of collectors to run
 */
export const start = async (
	id: string,
	{
		fullPageLoad = true,
		collectors = [],
	}: { fullPageLoad?: boolean; collectors?: Collector[] } = {}
): Promise< void > => {
	// There is a report in progress for this key, ignore this second call.
	if ( inFlightReporters.has( id ) ) {
		return;
	}

	const report = fullPageLoad
		? ReportImpl.fromPageStart( id, collectors )
		: ReportImpl.fromNow( id, collectors );
	inFlightReporters.set( id, report );
};

/**
 * Stops a report and sends it to the transporter.
 * @param id id of the report to send, comes from `start()`
 * @param obj options
 * @param obj.collectors list of collectors to run
 * @returns `true` if the report was sent successfully, `false` otherwise
 */
export const stop = async (
	id: string,
	{ collectors = [] }: { collectors?: Collector[] } = {}
): Promise< boolean > => {
	const existingReport = inFlightReporters.get( id );

	// There is no in progress report with the key, fail silently to avoid messing with the rendering
	if ( ! existingReport ) {
		return false;
	}

	inFlightReporters.delete( id );

	// The report may be still starting, wait for it.
	const startedReport = await existingReport;

	const payload = await startedReport.stop( collectors );

	return send( payload );
};

export type { Collector, Report, ReportData, ReportPayload };