Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix deploy metrics #74

Merged
merged 6 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 24 additions & 17 deletions app/src/features/toolbar/hooks/useDeployContract.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { ContractFactory, JsonAbi, StorageSlot } from 'fuels';
import { useMutation } from '@tanstack/react-query';
import { useConnectors, useFuel, useWallet } from '@fuels/react';
import { useFuel, useWallet } from '@fuels/react';
import { track } from '@vercel/analytics/react';
import { useMemo } from 'react';
import { useEffect, useState } from 'react';
import { toMetricProperties } from '../../../utils/metrics';

const DEPLOYMENT_TIMEOUT_MS = 120000;

Expand All @@ -21,30 +22,34 @@ export function useDeployContract(
) {
const { wallet, isLoading: walletIsLoading } = useWallet();
const { fuel } = useFuel();
const { connectors } = useConnectors();
const [metricMetadata, setMetricMetadata] = useState({});

const walletName = useMemo(() => {
const currentConnector = connectors.find(
(connector) => connector.connected
);
return !!wallet && !!currentConnector ? currentConnector.name : 'none';
}, [connectors, wallet]);
useEffect(() => {
const waitForMetadata = async () => {
const name = fuel.currentConnector()?.name ?? 'none';
const networkUrl = wallet?.provider.url ?? 'none';
const version = (await wallet?.provider.getVersion()) ?? 'none';
setMetricMetadata({ name, version, networkUrl });
};
waitForMetadata();
}, [wallet, fuel]);

const mutation = useMutation({
// Retry once if the wallet is still loading.
retry: walletIsLoading && !wallet ? 1 : 0,
onSuccess,
onError: (error) => {
track('Deploy Error', { source: error.name, walletName });
track('Deploy Error', toMetricProperties(error, metricMetadata));
onError(error);
},
mutationFn: async () => {
const { url: networkUrl } = await fuel.currentNetwork();
if (!wallet) {
if (walletIsLoading) {
updateLog('Connecting to wallet...');
} else {
throw new Error('Failed to connect to wallet');
throw new Error('Failed to connect to wallet', {
cause: { source: 'wallet' },
});
}
}

Expand All @@ -62,21 +67,23 @@ export function useDeployContract(
});
resolve({
contractId: contract.id.toB256(),
networkUrl,
networkUrl: contract.provider.url,
});
} catch (error) {
track('Deploy Error', { source: 'sdk', networkUrl, walletName });
} catch (error: any) {
// This is a hack to handle the case where the deployment failed because the user rejected the transaction.
const source = error.code === 0 ? 'user' : 'sdk';
error.cause = { source };
reject(error);
}
}
);

const timeoutPromise = new Promise((_resolve, reject) =>
setTimeout(() => {
track('Deploy Error', { source: 'timeout', networkUrl, walletName });
reject(
new Error(
`Request timed out after ${DEPLOYMENT_TIMEOUT_MS / 1000} seconds`
`Request timed out after ${DEPLOYMENT_TIMEOUT_MS / 1000} seconds`,
{ cause: { source: 'timeout' } }
)
);
}, DEPLOYMENT_TIMEOUT_MS)
Expand Down
15 changes: 15 additions & 0 deletions app/src/utils/metrics.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { toMetricProperties } from './metrics';

describe(`test toMetricProperties`, () => {
test.each`
label | cause | metadata | expected
${'with metadata and cause'} | ${{ source: 'test' }} | ${{ other: 'other' }} | ${{ source: 'test', other: 'other' }}
${'with invalid cause'} | ${'str'} | ${undefined} | ${undefined}
${'without cause or metadata'} | ${undefined} | ${undefined} | ${undefined}
${'with cause only'} | ${{ source: 'test' }} | ${undefined} | ${{ source: 'test' }}
${'with metadata only'} | ${undefined} | ${{ other: 'other' }} | ${{ other: 'other' }}
`('$label', ({ cause, metadata, expected }) => {
const error = cause ? new Error('Test', { cause }) : new Error('Test');
expect(toMetricProperties(error, metadata)).toEqual(expected);
});
});
36 changes: 36 additions & 0 deletions app/src/utils/metrics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
type AllowedProperty = string | number | boolean | null;

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}

function isAllowedEntry(
entry: [string, unknown]
): entry is [string, AllowedProperty] {
const value = entry[1];
return (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean' ||
value === null
);
}

export function toMetricProperties(
error: Error,
metadata?: Record<string, unknown>
): Record<string, AllowedProperty> | undefined {
const combined = { ...metadata };
if (isRecord(error.cause)) {
Object.assign(combined, error.cause);
}
if (!!Object.keys(combined).length) {
return Object.entries(combined)
.filter(isAllowedEntry)
.reduce((acc: Record<string, AllowedProperty>, [key, value]) => {
acc[key] = value;
return acc;
}, {});
}
return undefined;
}
Loading