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

feat: support optimistic concurrency control headers #3462

Draft
wants to merge 19 commits into
base: master
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion internal/fuel-core/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.40.1
git:1897-rpc-consistency-proposal~3
17 changes: 17 additions & 0 deletions packages/account/src/providers/provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2281,4 +2281,21 @@ Supported fuel-core version: ${mock.supportedVersion}.`

expect(fetchChainAndNodeInfo).toHaveBeenCalledTimes(2);
});

test('should ensure required block height will be validated', async () => {
await expectToThrowFuelError(
() =>
setupTestProviderAndWallets({
providerOptions: {
requestMiddleware: (request) => {
request.headers = {
REQUIRED_FUEL_BLOCK_HEIGHT: '99999999',
};
return request;
},
},
}),
new FuelError(ErrorCode.INVALID_REQUEST, 'Block height precondition failed')
);
});
});
61 changes: 44 additions & 17 deletions packages/account/src/providers/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ import { checkFuelCoreVersionCompatibility, versions } from '@fuel-ts/versions';
import { equalBytes } from '@noble/curves/abstract/utils';
import type { DocumentNode } from 'graphql';
import { GraphQLClient } from 'graphql-request';
import type { GraphQLClientResponse, GraphQLResponse } from 'graphql-request/src/types';
import type {
GraphQLClientRequestHeaders,
GraphQLClientResponse,
GraphQLResponse,
} from 'graphql-request/src/types';
import gql from 'graphql-tag';
import { clone } from 'ramda';

Expand Down Expand Up @@ -61,7 +65,13 @@ import {
} from './utils';
import type { RetryOptions } from './utils/auto-retry-fetch';
import { autoRetryFetch } from './utils/auto-retry-fetch';
import { handleGqlErrorMessage } from './utils/handle-gql-error-message';
import {
extractResponseBlockHeight,
isResponseError,
handleResponseError,
extractOperationDefinition,
isBlockSensitiveOperation,
} from './utils/handle-gql-error-message';
import { validatePaginationArgs } from './utils/validate-pagination-args';

const MAX_RETRIES = 10;
Expand Down Expand Up @@ -375,7 +385,9 @@ type ChainInfoCache = Record<string, ChainInfo>;
*/
type NodeInfoCache = Record<string, NodeInfo>;

type Operations = ReturnType<typeof getOperationsSdk>;
export type Operations = ReturnType<typeof getOperationsSdk>;

export type OperationsNames = keyof ReturnType<typeof getOperationsSdk>;

type SdkOperations = Omit<
Operations,
Expand Down Expand Up @@ -422,6 +434,8 @@ export default class Provider {
/** @hidden */
private static nodeInfoCache: NodeInfoCache = {};

private currentBlockHeight?: string;

/** @hidden */
public consensusParametersTimestamp?: number;

Expand Down Expand Up @@ -677,33 +691,46 @@ Supported fuel-core version: ${supportedVersion}.`
fetch: (input: RequestInfo | URL, requestInit?: RequestInit) =>
fetchFn(input.toString(), requestInit || {}, this.options),
responseMiddleware: (response: GraphQLClientResponse<unknown> | Error) => {
if ('response' in response) {
const graphQlResponse = response.response as GraphQLResponse;

if (Array.isArray(graphQlResponse?.errors)) {
for (const error of graphQlResponse.errors) {
handleGqlErrorMessage(error.message, error);
}
if (isResponseError(response)) {
handleResponseError(response);
} else {
const responseBlockHeight = extractResponseBlockHeight(
response as GraphQLClientResponse<unknown>
);

/**
* TODO:
* 1 - Evaluate if we should update this only on certain operation responses.
* 2 - Only update `responseBlockHeight` if it's greater than the current one.
*/
if (responseBlockHeight) {
this.currentBlockHeight = responseBlockHeight;
}
}
},
});

const executeQuery = (query: DocumentNode, vars: Record<string, unknown>) => {
const opDefinition = query.definitions.find((x) => x.kind === 'OperationDefinition') as {
operation: string;
};
const executeOperation = (operation: DocumentNode, vars: Record<string, unknown>) => {
const opDefinition = extractOperationDefinition(operation.definitions);
const isSubscription = opDefinition?.operation === 'subscription';

if (isSubscription) {
return FuelGraphqlSubscriber.create({
url: this.urlWithoutAuth,
query,
query: operation,
fetchFn: (url, requestInit) => fetchFn(url as string, requestInit, this.options),
variables: vars,
});
}
return gqlClient.request(query, vars);

if (isBlockSensitiveOperation(opDefinition) && this.currentBlockHeight) {
this.options.headers = this.options.headers ?? {};
Object.assign(this.options.headers, {
REQUIRED_FUEL_BLOCK_HEIGHT: this.currentBlockHeight,
});
}

return gqlClient.request(operation, vars);
};

const customOperations = (requester: Requester) => ({
Expand Down Expand Up @@ -732,7 +759,7 @@ Supported fuel-core version: ${supportedVersion}.`
});

// @ts-expect-error This is due to this function being generic. Its type is specified when calling a specific operation via provider.operations.xyz.
return { ...getOperationsSdk(executeQuery), ...customOperations(executeQuery) };
return { ...getOperationsSdk(executeOperation), ...customOperations(executeOperation) };
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
import { ErrorCode, FuelError } from '@fuel-ts/errors';
import type { GraphQLError } from 'graphql';
import type { DefinitionNode, GraphQLError, OperationDefinitionNode } from 'graphql';
import type { GraphQLClientResponse } from 'graphql-request/src/types';

import type { OperationsNames } from '../provider';

export interface FuelCoreGraphQLResponseHeader extends Headers {
current_fuel_block_height?: string;
}

export interface FuelCoreGraphQLResponse extends GraphQLClientResponse<unknown> {
headers: FuelCoreGraphQLResponseHeader;
}

interface GraphQLResponseError extends GraphQLClientResponse<unknown> {
response: GraphQLClientResponse<unknown>;
}

const BLOCK_SENSITIVE_OPERATIONS: OperationsNames[] = [
// TODO: Add block sensitive operations
'getCoinsToSpend',
];

export enum GqlErrorMessage {
NOT_ENOUGH_COINS = 'not enough coins to fit the target',
Expand All @@ -26,3 +46,38 @@ export const handleGqlErrorMessage = (errorMessage: string, rawError: GraphQLErr
throw new FuelError(ErrorCode.INVALID_REQUEST, errorMessage);
}
};

export const isResponseError = (
response: GraphQLClientResponse<unknown> | Error
): response is GraphQLResponseError => 'response' in response;

export const handleResponseError = (response: GraphQLResponseError) => {
const { response: responseError } = response;
if (responseError.status === 412) {
throw new FuelError(ErrorCode.INVALID_REQUEST, 'Block height precondition failed');
}

if (Array.isArray(responseError?.errors)) {
for (const error of responseError.errors) {
handleGqlErrorMessage(error.message, error);
}
}
};

export const extractResponseBlockHeight = (response: FuelCoreGraphQLResponse): string | null => {
const { headers } = response;
return headers.get('current_fuel_block_height');
};

export const extractOperationDefinition = (
definitions: ReadonlyArray<DefinitionNode>
): OperationDefinitionNode => {
const opDefinition = definitions.find(
(def) => def.kind === 'OperationDefinition'
) as OperationDefinitionNode;

return opDefinition;
};

export const isBlockSensitiveOperation = (operation: OperationDefinitionNode): boolean =>
BLOCK_SENSITIVE_OPERATIONS.includes((operation.name?.value || '') as OperationsNames);
2 changes: 1 addition & 1 deletion packages/versions/src/lib/getBuiltinVersions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Versions } from './types';
export function getBuiltinVersions(): Versions {
return {
FORC: '0.66.5',
FUEL_CORE: '0.40.1',
FUEL_CORE: 'git:1897-rpc-consistency-proposal',
FUELS: '0.97.2',
};
}
Loading