UNPKG

2.57 kBJavaScriptView Raw
1"use strict";
2/**
3 * Copyright 2019, OpenCensus Authors
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17Object.defineProperty(exports, "__esModule", { value: true });
18exports.TEST_ONLY = exports.timestampFromMillis = exports.getTimestampWithProcessHRTime = void 0;
19const MILLIS_PER_SECOND = 1e3;
20const NANOS_PER_MILLI = 1e3 * 1e3;
21const NANOS_PER_SECOND = 1e3 * 1e3 * 1e3;
22let hrtime = process.hrtime;
23let hrtimeOrigin = [0, 0];
24let hrtimeRefSeconds = 0;
25let hrtimeRefNanos = 0;
26function setHrtimeReference() {
27 resetHrtimeFunctionCache();
28 hrtimeOrigin = hrtime();
29 const refTime = Date.now();
30 hrtimeRefSeconds = Math.floor(refTime / MILLIS_PER_SECOND);
31 hrtimeRefNanos = (refTime % MILLIS_PER_SECOND) * NANOS_PER_MILLI;
32}
33/**
34 * This is used to enable tests to mock process.hrtime while still allow us to
35 * cache it.
36 */
37function resetHrtimeFunctionCache() {
38 hrtime = process.hrtime;
39}
40/**
41 * Gets the current timestamp with seconds and nanoseconds.
42 *
43 * @returns The Timestamp.
44 */
45function getTimestampWithProcessHRTime() {
46 const [offsetSecs, offsetNanos] = hrtime(hrtimeOrigin);
47 // determine drift in seconds and nanoseconds
48 const seconds = hrtimeRefSeconds + offsetSecs;
49 const nanos = hrtimeRefNanos + offsetNanos;
50 if (nanos >= NANOS_PER_SECOND) {
51 return { seconds: seconds + 1, nanos: nanos % NANOS_PER_SECOND };
52 }
53 return { seconds, nanos };
54}
55exports.getTimestampWithProcessHRTime = getTimestampWithProcessHRTime;
56/**
57 * Creates a new timestamp from the given milliseconds.
58 *
59 * @param epochMilli the timestamp represented in milliseconds since epoch.
60 * @returns new timestamp with specified fields.
61 */
62function timestampFromMillis(epochMilli) {
63 return {
64 seconds: Math.floor(epochMilli / MILLIS_PER_SECOND),
65 nanos: (epochMilli % MILLIS_PER_SECOND) * NANOS_PER_MILLI,
66 };
67}
68exports.timestampFromMillis = timestampFromMillis;
69setHrtimeReference();
70exports.TEST_ONLY = {
71 setHrtimeReference,
72 resetHrtimeFunctionCache,
73};
74//# sourceMappingURL=time-util.js.map
\No newline at end of file