Skip to content

Commit

Permalink
fix: add setBigUint64 polyfill (#577)
Browse files Browse the repository at this point in the history
* fix: add setBigUint64 polyfill

* test: makeNonce setBigUint64 polyfill

* test: update makeNonce polyfill test (should create same value)
  • Loading branch information
mstrasinskis committed Jun 3, 2022
1 parent c31a4cb commit 3a907af
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 7 deletions.
48 changes: 42 additions & 6 deletions packages/agent/src/agent/http/http.test.ts
Expand Up @@ -362,10 +362,46 @@ describe('replace identity', () => {
expect(mockFetch).toBeCalledTimes(1);
});
});
describe('makeNonce should create unique values', () => {
const nonces = new Set();
for (let i = 0; i < 100; i++) {
nonces.add(toHexString(makeNonce()));
}
expect(nonces.size).toBe(100);

describe('makeNonce', () => {
it('should create unique values', () => {
const nonces = new Set();
for (let i = 0; i < 100; i++) {
nonces.add(toHexString(makeNonce()));
}
expect(nonces.size).toBe(100);
});

describe('setBigUint64 polyfill', () => {
const DataViewConstructor = DataView;
let spyOnSetUint32: jest.SpyInstance;
let usePolyfill = false;

beforeAll(() => {
jest.spyOn(Math, 'random').mockImplementation(() => 0.5);
jest.spyOn(globalThis, 'DataView').mockImplementation(buffer => {
const view: DataView = new DataViewConstructor(buffer);
view.setBigUint64 = usePolyfill ? undefined : view.setBigUint64;
spyOnSetUint32 = jest.spyOn(view, 'setUint32');
return view;
});
});

afterAll(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});

it('should create same value using polyfill', () => {
const originalNonce = toHexString(makeNonce());
expect(spyOnSetUint32).toBeCalledTimes(2);

usePolyfill = true;

const nonce = toHexString(makeNonce());
expect(spyOnSetUint32).toBeCalledTimes(4);

expect(nonce).toBe(originalNonce);
});
});
});
9 changes: 8 additions & 1 deletion packages/agent/src/agent/http/types.ts
Expand Up @@ -110,7 +110,14 @@ export function makeNonce(): Nonce {
const now = BigInt(+Date.now());
const randHi = Math.floor(Math.random() * 0xffffffff);
const randLo = Math.floor(Math.random() * 0xffffffff);
view.setBigUint64(0, now);
// Fix for IOS < 14.8 setBigUint64 absence
if (typeof view.setBigUint64 === 'function') {
view.setBigUint64(0, now);
} else {
const TWO_TO_THE_32 = BigInt(1) << BigInt(32);
view.setUint32(0, Number(now >> BigInt(32)));
view.setUint32(4, Number(now % TWO_TO_THE_32));
}
view.setUint32(8, randHi);
view.setUint32(12, randLo);

Expand Down

0 comments on commit 3a907af

Please sign in to comment.