From b438c2d8aa28b4e38a91a0295c37d62d19e75788 Mon Sep 17 00:00:00 2001 From: Maneesh Tewani Date: Wed, 25 Nov 2026 14:24:30 -0800 Subject: [PATCH] feat(app,firestore,util): add contextual error support --- common/api-review/app.api.md | 3 + common/api-review/firestore-lite.api.md | 24 +- common/api-review/firestore.api.md | 24 +- common/api-review/util.api.md | 16 +- docs-devsite/_toc.yaml | 4 + docs-devsite/app.md | 22 + docs-devsite/firestore.firestoreerror.md | 4 +- .../firestore.firestoreerrorcontext.md | 42 ++ docs-devsite/firestore.md | 28 + docs-devsite/firestore_lite.firestoreerror.md | 4 +- .../firestore_lite.firestoreerrorcontext.md | 42 ++ docs-devsite/firestore_lite.md | 28 + packages/app/src/api.ts | 7 +- packages/firestore/externs.json | 1 + packages/firestore/lite/index.ts | 7 +- packages/firestore/src/api.ts | 7 +- packages/firestore/src/api/aggregate.ts | 40 +- packages/firestore/src/api/pipeline_impl.ts | 112 ++-- packages/firestore/src/api/reference_impl.ts | 365 +++++++---- .../firestore/src/core/firestore_client.ts | 7 +- packages/firestore/src/core/query.ts | 10 + packages/firestore/src/core/transaction.ts | 19 +- packages/firestore/src/lite-api/aggregate.ts | 40 +- .../firestore/src/lite-api/pipeline_impl.ts | 67 +- .../firestore/src/lite-api/reference_impl.ts | 244 +++---- packages/firestore/src/lite-api/stage.ts | 42 +- .../firestore/src/lite-api/transaction.ts | 172 ++--- .../firestore/src/lite-api/write_batch.ts | 135 ++-- packages/firestore/src/model/mutation.ts | 47 ++ packages/firestore/src/util/async_observer.ts | 10 +- packages/firestore/src/util/error.ts | 82 ++- packages/firestore/src/util/log.ts | 2 - .../test/unit/api/contextual_errors.test.ts | 599 ++++++++++++++++++ packages/util/src/errors.ts | 36 +- packages/util/test/errors.test.ts | 45 +- 35 files changed, 1829 insertions(+), 508 deletions(-) create mode 100644 docs-devsite/firestore.firestoreerrorcontext.md create mode 100644 docs-devsite/firestore_lite.firestoreerrorcontext.md create mode 100644 packages/firestore/test/unit/api/contextual_errors.test.ts diff --git a/common/api-review/app.api.md b/common/api-review/app.api.md index b7f59d1688..7e9e869f88 100644 --- a/common/api-review/app.api.md +++ b/common/api-review/app.api.md @@ -34,6 +34,9 @@ export const _DEFAULT_ENTRY_NAME = "[DEFAULT]"; // @public export function deleteApp(app: FirebaseApp): Promise; +// @public (undocumented) +export function enableContextualErrors(enabled: boolean): void; + // @public export interface FirebaseApp { automaticDataCollectionEnabled: boolean; diff --git a/common/api-review/firestore-lite.api.md b/common/api-review/firestore-lite.api.md index 02e6eaff5f..dc1a200729 100644 --- a/common/api-review/firestore-lite.api.md +++ b/common/api-review/firestore-lite.api.md @@ -359,7 +359,7 @@ DbModelType extends DocumentData = DocumentData } // @public -export class FirestoreError extends FirebaseError { +export class FirestoreError extends FirebaseError { readonly code: FirestoreErrorCode; readonly message: string; readonly stack?: string; @@ -384,6 +384,28 @@ export type FirestoreErrorCode = | 'data-loss' | 'unauthenticated'; +// @public +export interface FirestoreErrorContext { + // (undocumented) + operation?: FirestoreOperation; + // (undocumented) + path?: string; +} + +// @public +export enum FirestoreOperation { + // (undocumented) + DELETE = 'delete', + // (undocumented) + LIST = 'list', + // (undocumented) + READ = 'read', + // (undocumented) + UPDATE = 'update', + // (undocumented) + WRITE = 'write' +} + // @public export class GeoPoint { constructor(latitude: number, longitude: number); diff --git a/common/api-review/firestore.api.md b/common/api-review/firestore.api.md index 6c84b56cdd..2749ee8e69 100644 --- a/common/api-review/firestore.api.md +++ b/common/api-review/firestore.api.md @@ -437,7 +437,7 @@ DbModelType extends DocumentData = DocumentData } // @public -export class FirestoreError extends FirebaseError { +export class FirestoreError extends FirebaseError { readonly code: FirestoreErrorCode; readonly message: string; readonly stack?: string; @@ -462,11 +462,33 @@ export type FirestoreErrorCode = | 'data-loss' | 'unauthenticated'; +// @public +export interface FirestoreErrorContext { + // (undocumented) + operation?: FirestoreOperation; + // (undocumented) + path?: string; +} + // @public export type FirestoreLocalCache = | MemoryLocalCache | PersistentLocalCache; +// @public +export enum FirestoreOperation { + // (undocumented) + DELETE = 'delete', + // (undocumented) + LIST = 'list', + // (undocumented) + READ = 'read', + // (undocumented) + UPDATE = 'update', + // (undocumented) + WRITE = 'write' +} + // @public export interface FirestoreSettings { cacheSizeBytes?: number; diff --git a/common/api-review/util.api.md b/common/api-review/util.api.md index 2d1452503e..f858bc5a71 100644 --- a/common/api-review/util.api.md +++ b/common/api-review/util.api.md @@ -140,6 +140,11 @@ export type EmulatorMockTokenOptions = ({ sub: string; }) & Partial; +// Warning: (ae-missing-release-tag) "enableContextualErrors" is part of the package's API, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export function enableContextualErrors(enableFlag: boolean): void; + // Warning: (ae-missing-release-tag) "ErrorData" is part of the package's API, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -207,11 +212,13 @@ export interface FirebaseDefaults { // Warning: (ae-missing-release-tag) "FirebaseError" is part of the package's API, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export class FirebaseError extends Error { +export class FirebaseError extends Error { constructor( code: string, message: string, - customData?: Record | undefined); + customData?: Record | undefined, _context?: T); readonly code: string; + // (undocumented) + readonly context?: T; customData?: Record | undefined; readonly name: string; } @@ -275,6 +282,11 @@ export function isCloudflareWorker(): boolean; // @public export function isCloudWorkstation(url: string): boolean; +// Warning: (ae-missing-release-tag) "isContextualErrorsEnabled" is part of the package's API, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export function isContextualErrorsEnabled(): boolean; + // Warning: (ae-missing-release-tag) "isElectron" is part of the package's API, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public diff --git a/docs-devsite/_toc.yaml b/docs-devsite/_toc.yaml index dd579a2a68..31f4ac44fe 100644 --- a/docs-devsite/_toc.yaml +++ b/docs-devsite/_toc.yaml @@ -541,6 +541,8 @@ toc: path: /docs/reference/js/firestore.firestoredataconverter.md - title: FirestoreError path: /docs/reference/js/firestore.firestoreerror.md + - title: FirestoreErrorContext + path: /docs/reference/js/firestore.firestoreerrorcontext.md - title: FirestoreSettings path: /docs/reference/js/firestore.firestoresettings.md - title: GeoPoint @@ -658,6 +660,8 @@ toc: path: /docs/reference/js/firestore_lite.firestoredataconverter.md - title: FirestoreError path: /docs/reference/js/firestore_lite.firestoreerror.md + - title: FirestoreErrorContext + path: /docs/reference/js/firestore_lite.firestoreerrorcontext.md - title: GeoPoint path: /docs/reference/js/firestore_lite.geopoint.md - title: Int32Value diff --git a/docs-devsite/app.md b/docs-devsite/app.md index 50994f1af1..8257dbc85a 100644 --- a/docs-devsite/app.md +++ b/docs-devsite/app.md @@ -25,6 +25,8 @@ This package coordinates the communication between the different Firebase compon | [initializeApp()](./app.md#initializeapp) | Creates and initializes a FirebaseApp instance. | | function(config, ...) | | [initializeServerApp(config)](./app.md#initializeserverapp_e7d0728) | Creates and initializes a [FirebaseServerApp](./app.firebaseserverapp.md#firebaseserverapp_interface) instance. | +| function(enabled, ...) | +| [enableContextualErrors(enabled)](./app.md#enablecontextualerrors_25adbe2) | | | function(libraryKeyOrName, ...) | | [registerVersion(libraryKeyOrName, version, variant)](./app.md#registerversion_f673248) | Registers a library's name and version for platform logging purposes. | | function(logCallback, ...) | @@ -150,6 +152,26 @@ If [FirebaseServerAppSettings.releaseOnDeref](./app.firebaseserverappsettings.md If the `FIREBASE_OPTIONS` environment variable does not contain a valid project configuration required for auto-initialization. +## function(enabled, ...) + +### enableContextualErrors(enabled) {:#enablecontextualerrors_25adbe2} + +Signature: + +```typescript +export declare function enableContextualErrors(enabled: boolean): void; +``` + +#### Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| enabled | boolean | | + +Returns: + +void + ## function(libraryKeyOrName, ...) ### registerVersion(libraryKeyOrName, version, variant) {:#registerversion_f673248} diff --git a/docs-devsite/firestore.firestoreerror.md b/docs-devsite/firestore.firestoreerror.md index 54b0bfb7bd..f217f0d3d4 100644 --- a/docs-devsite/firestore.firestoreerror.md +++ b/docs-devsite/firestore.firestoreerror.md @@ -15,9 +15,9 @@ An error returned by a Firestore operation. Signature: ```typescript -export declare class FirestoreError extends FirebaseError +export declare class FirestoreError extends FirebaseError ``` -Extends: [FirebaseError](./util.firebaseerror.md#firebaseerror_class) +Extends: [FirebaseError](./util.firebaseerror.md#firebaseerror_class)<[FirestoreErrorContext](./firestore.firestoreerrorcontext.md#firestoreerrorcontext_interface)> ## Properties diff --git a/docs-devsite/firestore.firestoreerrorcontext.md b/docs-devsite/firestore.firestoreerrorcontext.md new file mode 100644 index 0000000000..9ca3be421e --- /dev/null +++ b/docs-devsite/firestore.firestoreerrorcontext.md @@ -0,0 +1,42 @@ +Project: /docs/reference/js/_project.yaml +Book: /docs/reference/_book.yaml +page_type: reference + +{% comment %} +DO NOT EDIT THIS FILE! +This is generated by the JS SDK team, and any local changes will be +overwritten. Changes should be made in the source code at +https://github.com/firebase/firebase-js-sdk +{% endcomment %} + +# FirestoreErrorContext interface +Contextual information attached to a [FirestoreError](./firestore.firestoreerror.md#firestoreerror_class) when contextual errors are enabled. + +Signature: + +```typescript +export declare interface FirestoreErrorContext +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [operation](./firestore.firestoreerrorcontext.md#firestoreerrorcontextoperation) | [FirestoreOperation](./firestore.md#firestoreoperation) | | +| [path](./firestore.firestoreerrorcontext.md#firestoreerrorcontextpath) | string | | + +## FirestoreErrorContext.operation + +Signature: + +```typescript +operation?: FirestoreOperation; +``` + +## FirestoreErrorContext.path + +Signature: + +```typescript +path?: string; +``` diff --git a/docs-devsite/firestore.md b/docs-devsite/firestore.md index 8eb58da90e..46aed48152 100644 --- a/docs-devsite/firestore.md +++ b/docs-devsite/firestore.md @@ -183,6 +183,12 @@ Cloud Firestore | [VectorValue](./firestore.vectorvalue.md#vectorvalue_class) | Represents a vector type in Firestore documents. Create an instance with [vector()](./firestore.md#vector_0dbdaf2). | | [WriteBatch](./firestore.writebatch.md#writebatch_class) | A write batch, used to perform multiple writes as a single atomic unit.A WriteBatch object can be acquired by calling [writeBatch()](./firestore.md#writebatch_231a8e0). It provides methods for adding writes to the write batch. None of the writes will be committed (or visible locally) until [WriteBatch.commit()](./firestore.writebatch.md#writebatchcommit) is called. | +## Enumerations + +| Enumeration | Description | +| --- | --- | +| [FirestoreOperation](./firestore.md#firestoreoperation) | The Firestore operation associated with a [FirestoreErrorContext](./firestore.firestoreerrorcontext.md#firestoreerrorcontext_interface). | + ## Interfaces | Interface | Description | @@ -192,6 +198,7 @@ Cloud Firestore | [DocumentData](./firestore.documentdata.md#documentdata_interface) | Document data (for use with [setDoc()](./firestore_lite.md#setdoc_ee215ad)) consists of fields mapped to values. | | [ExperimentalLongPollingOptions](./firestore.experimentallongpollingoptions.md#experimentallongpollingoptions_interface) | Options that configure the SDK’s underlying network transport (WebChannel) when long-polling is used.Note: This interface is "experimental" and is subject to change.See FirestoreSettings.experimentalAutoDetectLongPolling, FirestoreSettings.experimentalForceLongPolling, and FirestoreSettings.experimentalLongPollingOptions. | | [FirestoreDataConverter](./firestore.firestoredataconverter.md#firestoredataconverter_interface) | Converter used by withConverter() to transform user objects of type AppModelType into Firestore data of type DbModelType.Using the converter allows you to specify generic type arguments when storing and retrieving objects from Firestore.In this context, an "AppModel" is a class that is used in an application to package together related information and functionality. Such a class could, for example, have properties with complex, nested data types, properties used for memoization, properties of types not supported by Firestore (such as symbol and bigint), and helper functions that perform compound operations. Such classes are not suitable and/or possible to store into a Firestore database. Instead, instances of such classes need to be converted to "plain old JavaScript objects" (POJOs) with exclusively primitive properties, potentially nested inside other POJOs or arrays of POJOs. In this context, this type is referred to as the "DbModel" and would be an object suitable for persisting into Firestore. For convenience, applications can implement FirestoreDataConverter and register the converter with Firestore objects, such as DocumentReference or Query, to automatically convert AppModel to DbModel when storing into Firestore, and convert DbModel to AppModel when retrieving from Firestore. | +| [FirestoreErrorContext](./firestore.firestoreerrorcontext.md#firestoreerrorcontext_interface) | Contextual information attached to a [FirestoreError](./firestore.firestoreerror.md#firestoreerror_class) when contextual errors are enabled. | | [FirestoreSettings](./firestore.firestoresettings.md#firestoresettings_interface) | Specifies custom configurations for your Cloud Firestore instance. You must set these before invoking any other methods. | | [Index](./firestore.index.md#index_interface) | (Public Preview) The SDK definition of a Firestore index. | | [IndexConfiguration](./firestore.indexconfiguration.md#indexconfiguration_interface) | (Public Preview) A list of Firestore indexes to speed up local query execution.See [JSON Format](https://firebase.google.com/docs/reference/firestore/indexes/#json_format) for a description of the format of the index definition. | @@ -3671,3 +3678,24 @@ export declare type WithFieldValue = } : never); ``` + +## FirestoreOperation + +The Firestore operation associated with a [FirestoreErrorContext](./firestore.firestoreerrorcontext.md#firestoreerrorcontext_interface). + +Signature: + +```typescript +export declare enum FirestoreOperation +``` + +## Enumeration Members + +| Member | Value | Description | +| --- | --- | --- | +| DELETE | 'delete' | | +| LIST | 'list' | | +| READ | 'read' | | +| UPDATE | 'update' | | +| WRITE | 'write' | | + diff --git a/docs-devsite/firestore_lite.firestoreerror.md b/docs-devsite/firestore_lite.firestoreerror.md index e3c6dd2302..a6eeb792ac 100644 --- a/docs-devsite/firestore_lite.firestoreerror.md +++ b/docs-devsite/firestore_lite.firestoreerror.md @@ -15,9 +15,9 @@ An error returned by a Firestore operation. Signature: ```typescript -export declare class FirestoreError extends FirebaseError +export declare class FirestoreError extends FirebaseError ``` -Extends: [FirebaseError](./util.firebaseerror.md#firebaseerror_class) +Extends: [FirebaseError](./util.firebaseerror.md#firebaseerror_class)<[FirestoreErrorContext](./firestore_lite.firestoreerrorcontext.md#firestoreerrorcontext_interface)> ## Properties diff --git a/docs-devsite/firestore_lite.firestoreerrorcontext.md b/docs-devsite/firestore_lite.firestoreerrorcontext.md new file mode 100644 index 0000000000..33fe5b3ebe --- /dev/null +++ b/docs-devsite/firestore_lite.firestoreerrorcontext.md @@ -0,0 +1,42 @@ +Project: /docs/reference/js/_project.yaml +Book: /docs/reference/_book.yaml +page_type: reference + +{% comment %} +DO NOT EDIT THIS FILE! +This is generated by the JS SDK team, and any local changes will be +overwritten. Changes should be made in the source code at +https://github.com/firebase/firebase-js-sdk +{% endcomment %} + +# FirestoreErrorContext interface +Contextual information attached to a [FirestoreError](./firestore_lite.firestoreerror.md#firestoreerror_class) when contextual errors are enabled. + +Signature: + +```typescript +export declare interface FirestoreErrorContext +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [operation](./firestore_lite.firestoreerrorcontext.md#firestoreerrorcontextoperation) | [FirestoreOperation](./firestore_lite.md#firestoreoperation) | | +| [path](./firestore_lite.firestoreerrorcontext.md#firestoreerrorcontextpath) | string | | + +## FirestoreErrorContext.operation + +Signature: + +```typescript +operation?: FirestoreOperation; +``` + +## FirestoreErrorContext.path + +Signature: + +```typescript +path?: string; +``` diff --git a/docs-devsite/firestore_lite.md b/docs-devsite/firestore_lite.md index 8b036ec4b1..161c9ac93b 100644 --- a/docs-devsite/firestore_lite.md +++ b/docs-devsite/firestore_lite.md @@ -134,6 +134,12 @@ Firestore Lite is a small online-only SDK that allows read and write access to y | [VectorValue](./firestore_lite.vectorvalue.md#vectorvalue_class) | Represents a vector type in Firestore documents. Create an instance with [vector()](./firestore_lite.md#vector_0dbdaf2). | | [WriteBatch](./firestore_lite.writebatch.md#writebatch_class) | A write batch, used to perform multiple writes as a single atomic unit.A WriteBatch object can be acquired by calling [writeBatch()](./firestore_lite.md#writebatch_231a8e0). It provides methods for adding writes to the write batch. None of the writes will be committed (or visible locally) until [WriteBatch.commit()](./firestore_lite.writebatch.md#writebatchcommit) is called. | +## Enumerations + +| Enumeration | Description | +| --- | --- | +| [FirestoreOperation](./firestore_lite.md#firestoreoperation) | The Firestore operation associated with a [FirestoreErrorContext](./firestore_lite.firestoreerrorcontext.md#firestoreerrorcontext_interface). | + ## Interfaces | Interface | Description | @@ -141,6 +147,7 @@ Firestore Lite is a small online-only SDK that allows read and write access to y | [AggregateSpec](./firestore_lite.aggregatespec.md#aggregatespec_interface) | Specifies a set of aggregations and their aliases. | | [DocumentData](./firestore_lite.documentdata.md#documentdata_interface) | Document data (for use with [setDoc()](./firestore.md#setdoc_ee215ad)) consists of fields mapped to values. | | [FirestoreDataConverter](./firestore_lite.firestoredataconverter.md#firestoredataconverter_interface) | Converter used by withConverter() to transform user objects of type AppModelType into Firestore data of type DbModelType.Using the converter allows you to specify generic type arguments when storing and retrieving objects from Firestore.In this context, an "AppModel" is a class that is used in an application to package together related information and functionality. Such a class could, for example, have properties with complex, nested data types, properties used for memoization, properties of types not supported by Firestore (such as symbol and bigint), and helper functions that perform compound operations. Such classes are not suitable and/or possible to store into a Firestore database. Instead, instances of such classes need to be converted to "plain old JavaScript objects" (POJOs) with exclusively primitive properties, potentially nested inside other POJOs or arrays of POJOs. In this context, this type is referred to as the "DbModel" and would be an object suitable for persisting into Firestore. For convenience, applications can implement FirestoreDataConverter and register the converter with Firestore objects, such as DocumentReference or Query, to automatically convert AppModel to DbModel when storing into Firestore, and convert DbModel to AppModel when retrieving from Firestore. | +| [FirestoreErrorContext](./firestore_lite.firestoreerrorcontext.md#firestoreerrorcontext_interface) | Contextual information attached to a [FirestoreError](./firestore_lite.firestoreerror.md#firestoreerror_class) when contextual errors are enabled. | | [Settings](./firestore_lite.settings.md#settings_interface) | Specifies custom configurations for your Cloud Firestore instance. You must set these before invoking any other methods. | | [TransactionOptions](./firestore_lite.transactionoptions.md#transactionoptions_interface) | Options to customize transaction behavior. | @@ -2130,3 +2137,24 @@ export declare type WithFieldValue = } : never); ``` + +## FirestoreOperation + +The Firestore operation associated with a [FirestoreErrorContext](./firestore_lite.firestoreerrorcontext.md#firestoreerrorcontext_interface). + +Signature: + +```typescript +export declare enum FirestoreOperation +``` + +## Enumeration Members + +| Member | Value | Description | +| --- | --- | --- | +| DELETE | 'delete' | | +| LIST | 'list' | | +| READ | 'read' | | +| UPDATE | 'update' | | +| WRITE | 'write' | | + diff --git a/packages/app/src/api.ts b/packages/app/src/api.ts index efd053d767..e48a6754df 100644 --- a/packages/app/src/api.ts +++ b/packages/app/src/api.ts @@ -53,7 +53,8 @@ import { deepEqual, getDefaultAppConfig, isBrowser, - isWebWorker + isWebWorker, + enableContextualErrors as enableContextualErrorsImpl } from '@firebase/util'; export { FirebaseError } from '@firebase/util'; @@ -525,3 +526,7 @@ export function onLog( export function setLogLevel(logLevel: LogLevelString): void { setLogLevelImpl(logLevel); } + +export function enableContextualErrors(enabled: boolean): void { + enableContextualErrorsImpl(enabled); +} diff --git a/packages/firestore/externs.json b/packages/firestore/externs.json index 0332fdee75..1408977ad3 100644 --- a/packages/firestore/externs.json +++ b/packages/firestore/externs.json @@ -35,6 +35,7 @@ "packages/util/dist/src/defaults.d.ts", "packages/util/dist/src/emulator.d.ts", "packages/util/dist/src/environment.d.ts", + "packages/util/dist/src/errors.d.ts", "packages/util/dist/src/url.d.ts", "packages/util/dist/src/compat.d.ts", "packages/util/dist/src/global.d.ts", diff --git a/packages/firestore/lite/index.ts b/packages/firestore/lite/index.ts index 58d1f75133..996ba2f377 100644 --- a/packages/firestore/lite/index.ts +++ b/packages/firestore/lite/index.ts @@ -172,4 +172,9 @@ export { GeoPoint } from '../src/lite-api/geo_point'; export { Timestamp } from '../src/lite-api/timestamp'; -export { FirestoreErrorCode, FirestoreError } from '../src/util/error'; +export { + FirestoreErrorCode, + FirestoreError, + FirestoreErrorContext, + FirestoreOperation +} from '../src/util/error'; diff --git a/packages/firestore/src/api.ts b/packages/firestore/src/api.ts index ae8c063db4..55fbfac986 100644 --- a/packages/firestore/src/api.ts +++ b/packages/firestore/src/api.ts @@ -209,7 +209,12 @@ export { Timestamp } from './api/timestamp'; export { CACHE_SIZE_UNLIMITED } from './api/database'; -export { FirestoreError, FirestoreErrorCode } from './util/error'; +export { + FirestoreError, + FirestoreErrorCode, + FirestoreErrorContext, + FirestoreOperation +} from './util/error'; export { AbstractUserDataWriter } from './lite-api/user_data_writer'; diff --git a/packages/firestore/src/api/aggregate.ts b/packages/firestore/src/api/aggregate.ts index d747905106..d03e579a3b 100644 --- a/packages/firestore/src/api/aggregate.ts +++ b/packages/firestore/src/api/aggregate.ts @@ -17,6 +17,7 @@ import { AggregateImpl } from '../core/aggregate'; import { firestoreClientRunAggregateQuery } from '../core/firestore_client'; +import { queryErrorPath } from '../core/query'; import { count } from '../lite-api/aggregate'; import { AggregateField, @@ -25,6 +26,7 @@ import { } from '../lite-api/aggregate_types'; import { DocumentData, Query } from '../lite-api/reference'; import { ApiClientObjectMap, Value } from '../protos/firestore_proto_api'; +import { FirestoreOperation, withContextPromise } from '../util/error'; import { cast } from '../util/input_validation'; import { mapToArray } from '../util/obj'; @@ -123,23 +125,31 @@ export function getAggregateFromServer< AggregateQuerySnapshot > { const firestore = cast(query.firestore, Firestore); - const client = ensureFirestoreConfigured(firestore); + return withContextPromise( + { path: queryErrorPath(query._query), operation: FirestoreOperation.LIST }, + () => { + const client = ensureFirestoreConfigured(firestore); - const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => { - return new AggregateImpl( - alias, - aggregate.aggregateType, - aggregate._internalFieldPath - ); - }); + const internalAggregates = mapToArray( + aggregateSpec, + (aggregate, alias) => { + return new AggregateImpl( + alias, + aggregate.aggregateType, + aggregate._internalFieldPath + ); + } + ); - // Run the aggregation and convert the results - return firestoreClientRunAggregateQuery( - client, - query._query, - internalAggregates - ).then(aggregateResult => - convertToAggregateQuerySnapshot(firestore, query, aggregateResult) + // Run the aggregation and convert the results + return firestoreClientRunAggregateQuery( + client, + query._query, + internalAggregates + ).then(aggregateResult => + convertToAggregateQuerySnapshot(firestore, query, aggregateResult) + ); + } ); } diff --git a/packages/firestore/src/api/pipeline_impl.ts b/packages/firestore/src/api/pipeline_impl.ts index 665fca12b8..673a672eb3 100644 --- a/packages/firestore/src/api/pipeline_impl.ts +++ b/packages/firestore/src/api/pipeline_impl.ts @@ -25,12 +25,12 @@ import { Pipeline as LitePipeline } from '../lite-api/pipeline'; import { PipelineResult, PipelineSnapshot } from '../lite-api/pipeline-result'; import { PipelineSource } from '../lite-api/pipeline-source'; import { PipelineExecuteOptions } from '../lite-api/pipeline_options'; -import { Stage } from '../lite-api/stage'; +import { getPipelineErrorContext, Stage } from '../lite-api/stage'; import { newUserDataReader, UserDataSource } from '../lite-api/user_data_reader'; -import { Code, FirestoreError } from '../util/error'; +import { Code, FirestoreError, withContextPromise } from '../util/error'; import { cast } from '../util/input_validation'; import { ensureFirestoreConfigured, Firestore } from './database'; @@ -140,65 +140,69 @@ export function execute( const { pipeline, rawOptions, atomic, ...rest } = options; - if (!pipeline._db) { - return Promise.reject( - new FirestoreError( - Code.FAILED_PRECONDITION, - 'This pipeline was created without a database (e.g., as a subcollection pipeline) and cannot be executed directly. It can only be used as part of another pipeline.' - ) - ); - } + const errorContext = getPipelineErrorContext(pipeline.stages); - const firestore = cast(pipeline._db, Firestore); - const client = ensureFirestoreConfigured(firestore); + return withContextPromise(errorContext, () => { + if (!pipeline._db) { + return Promise.reject( + new FirestoreError( + Code.FAILED_PRECONDITION, + 'This pipeline was created without a database (e.g., as a subcollection pipeline) and cannot be executed directly. It can only be used as part of another pipeline.' + ) + ); + } - const userDataReader = newUserDataReader(firestore); - const context = userDataReader.createContext( - UserDataSource.Argument, - 'execute' - ); + const firestore = cast(pipeline._db, Firestore); + const client = ensureFirestoreConfigured(firestore); - pipeline._readUserData(context); - const userDataWriter = new ExpUserDataWriter(firestore); + const userDataReader = newUserDataReader(firestore); + const context = userDataReader.createContext( + UserDataSource.Argument, + 'execute' + ); - const structuredPipelineOptions = new StructuredPipelineOptions( - rest, - rawOptions - ); - structuredPipelineOptions._readUserData(context); + pipeline._readUserData(context); + const userDataWriter = new ExpUserDataWriter(firestore); - const structuredPipeline: StructuredPipeline = new StructuredPipeline( - pipeline, - structuredPipelineOptions - ); + const structuredPipelineOptions = new StructuredPipelineOptions( + rest, + rawOptions + ); + structuredPipelineOptions._readUserData(context); - return firestoreClientExecutePipeline(client, structuredPipeline, { - atomic - }).then(result => { - // Get the execution time from the first result. - // firestoreClientExecutePipeline returns at least one PipelineStreamElement - // even if the returned document set is empty. - const executionTime = - result.length > 0 ? result[0].executionTime?.toTimestamp() : undefined; - - const docs = result - // Currently ignore any response from ExecutePipeline that does - // not contain any document data in the `fields` property. - .filter(element => !!element.fields) - .map( - element => - new PipelineResult( - userDataWriter, - element.fields!, - element.key?.path - ? new DocumentReference(firestore, null, element.key) - : undefined, - element.createTime?.toTimestamp(), - element.updateTime?.toTimestamp() - ) - ); + const structuredPipeline: StructuredPipeline = new StructuredPipeline( + pipeline, + structuredPipelineOptions + ); - return new PipelineSnapshot(pipeline, docs, executionTime); + return firestoreClientExecutePipeline(client, structuredPipeline, { + atomic + }).then(result => { + // Get the execution time from the first result. + // firestoreClientExecutePipeline returns at least one PipelineStreamElement + // even if the returned document set is empty. + const executionTime = + result.length > 0 ? result[0].executionTime?.toTimestamp() : undefined; + + const docs = result + // Currently ignore any response from ExecutePipeline that does + // not contain any document data in the `fields` property. + .filter(element => !!element.fields) + .map( + element => + new PipelineResult( + userDataWriter, + element.fields!, + element.key?.path + ? new DocumentReference(firestore, null, element.key) + : undefined, + element.createTime?.toTimestamp(), + element.updateTime?.toTimestamp() + ) + ); + + return new PipelineSnapshot(pipeline, docs, executionTime); + }); }); } diff --git a/packages/firestore/src/api/reference_impl.ts b/packages/firestore/src/api/reference_impl.ts index 64ed629040..224726efba 100644 --- a/packages/firestore/src/api/reference_impl.ts +++ b/packages/firestore/src/api/reference_impl.ts @@ -35,7 +35,11 @@ import { firestoreClientListen, firestoreClientWrite } from '../core/firestore_client'; -import { Query as InternalQuery, newQueryForPath } from '../core/query'; +import { + Query as InternalQuery, + newQueryForPath, + queryErrorPath +} from '../core/query'; import { ViewSnapshot } from '../core/view_snapshot'; import { FieldPath } from '../lite-api/field_path'; import { validateHasExplicitOrderByForLimitToLast } from '../lite-api/query'; @@ -61,7 +65,15 @@ import { import { DocumentKey } from '../model/document_key'; import { DeleteMutation, Mutation, Precondition } from '../model/mutation'; import { debugAssert } from '../util/assert'; -import { Code, FirestoreError } from '../util/error'; +import { + Code, + FirestoreError, + FirestoreErrorContext, + FirestoreOperation, + withContext, + withContextPromise, + withContextSync +} from '../util/error'; import { cast } from '../util/input_validation'; import { ensureFirestoreConfigured, Firestore } from './database'; @@ -120,12 +132,17 @@ export function getDoc( DocumentReference ); const firestore = cast(reference.firestore, Firestore); - const client = ensureFirestoreConfigured(firestore); + return withContextPromise( + { path: reference.path, operation: FirestoreOperation.READ }, + () => { + const client = ensureFirestoreConfigured(firestore); - return firestoreClientGetDocumentViaSnapshotListener( - client, - reference._key - ).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot)); + return firestoreClientGetDocumentViaSnapshotListener( + client, + reference._key + ).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot)); + } + ); } /** @@ -143,22 +160,30 @@ export function getDocFromCache( DocumentReference ); const firestore = cast(reference.firestore, Firestore); - const client = ensureFirestoreConfigured(firestore); - const userDataWriter = new ExpUserDataWriter(firestore); + return withContextPromise( + { path: reference.path, operation: FirestoreOperation.READ }, + () => { + const client = ensureFirestoreConfigured(firestore); + const userDataWriter = new ExpUserDataWriter(firestore); - return firestoreClientGetDocumentFromLocalCache(client, reference._key).then( - doc => - new DocumentSnapshot( - firestore, - userDataWriter, - reference._key, - doc, - new SnapshotMetadata( - doc !== null && doc.hasLocalMutations, - /* fromCache= */ true - ), - reference.converter - ) + return firestoreClientGetDocumentFromLocalCache( + client, + reference._key + ).then( + doc => + new DocumentSnapshot( + firestore, + userDataWriter, + reference._key, + doc, + new SnapshotMetadata( + doc !== null && doc.hasLocalMutations, + /* fromCache= */ true + ), + reference.converter + ) + ); + } ); } @@ -180,11 +205,20 @@ export function getDocFromServer< DocumentReference ); const firestore = cast(reference.firestore, Firestore); - const client = ensureFirestoreConfigured(firestore); + return withContextPromise( + { path: reference.path, operation: FirestoreOperation.READ }, + () => { + const client = ensureFirestoreConfigured(firestore); - return firestoreClientGetDocumentViaSnapshotListener(client, reference._key, { - source: 'server' - }).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot)); + return firestoreClientGetDocumentViaSnapshotListener( + client, + reference._key, + { + source: 'server' + } + ).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot)); + } + ); } /** @@ -206,21 +240,26 @@ export function getDocs( ): Promise> { query = cast>(query, Query); const firestore = cast(query.firestore, Firestore); - const client = ensureFirestoreConfigured(firestore); - const userDataWriter = new ExpUserDataWriter(firestore); + return withContextPromise( + { path: queryErrorPath(query._query), operation: FirestoreOperation.LIST }, + () => { + const client = ensureFirestoreConfigured(firestore); + const userDataWriter = new ExpUserDataWriter(firestore); - validateHasExplicitOrderByForLimitToLast(query._query); - return firestoreClientGetDocumentsViaSnapshotListener( - client, - query._query - ).then( - snapshot => - new QuerySnapshot( - firestore, - userDataWriter, - query as Query, - snapshot - ) + validateHasExplicitOrderByForLimitToLast(query._query); + return firestoreClientGetDocumentsViaSnapshotListener( + client, + query._query + ).then( + snapshot => + new QuerySnapshot( + firestore, + userDataWriter, + query as Query, + snapshot + ) + ); + } ); } @@ -239,17 +278,25 @@ export function getDocsFromCache< ): Promise> { query = cast>(query, Query); const firestore = cast(query.firestore, Firestore); - const client = ensureFirestoreConfigured(firestore); - const userDataWriter = new ExpUserDataWriter(firestore); + return withContextPromise( + { path: queryErrorPath(query._query), operation: FirestoreOperation.LIST }, + () => { + const client = ensureFirestoreConfigured(firestore); + const userDataWriter = new ExpUserDataWriter(firestore); - return firestoreClientGetDocumentsFromLocalCache(client, query._query).then( - snapshot => - new QuerySnapshot( - firestore, - userDataWriter, - query, - snapshot - ) + return firestoreClientGetDocumentsFromLocalCache( + client, + query._query + ).then( + snapshot => + new QuerySnapshot( + firestore, + userDataWriter, + query, + snapshot + ) + ); + } ); } @@ -267,13 +314,23 @@ export function getDocsFromServer< ): Promise> { query = cast>(query, Query); const firestore = cast(query.firestore, Firestore); - const client = ensureFirestoreConfigured(firestore); - const userDataWriter = new ExpUserDataWriter(firestore); + return withContextPromise( + { path: queryErrorPath(query._query), operation: FirestoreOperation.LIST }, + () => { + const client = ensureFirestoreConfigured(firestore); + const userDataWriter = new ExpUserDataWriter(firestore); - return firestoreClientGetDocumentsViaSnapshotListener(client, query._query, { - source: 'server' - }).then( - snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot) + return firestoreClientGetDocumentsViaSnapshotListener( + client, + query._query, + { + source: 'server' + } + ).then( + snapshot => + new QuerySnapshot(firestore, userDataWriter, query, snapshot) + ); + } ); } @@ -348,24 +405,28 @@ export function setDoc( DocumentReference ); const firestore = cast(reference.firestore, Firestore); + return withContextPromise( + { path: reference.path, operation: FirestoreOperation.WRITE }, + () => { + const convertedValue = applyFirestoreDataConverter( + reference.converter, + data as WithFieldValue, + options + ); + const dataReader = newUserDataReader(firestore); + const parsed = parseSetData( + dataReader, + 'setDoc', + reference._key, + convertedValue, + reference.converter !== null, + options + ); - const convertedValue = applyFirestoreDataConverter( - reference.converter, - data as WithFieldValue, - options - ); - const dataReader = newUserDataReader(firestore); - const parsed = parseSetData( - dataReader, - 'setDoc', - reference._key, - convertedValue, - reference.converter !== null, - options + const mutation = parsed.toMutation(reference._key, Precondition.none()); + return executeWrite(firestore, [mutation]); + } ); - - const mutation = parsed.toMutation(reference._key, Precondition.none()); - return executeWrite(firestore, [mutation]); } /** @@ -448,37 +509,44 @@ export function updateDoc( DocumentReference ); const firestore = cast(reference.firestore, Firestore); + return withContextPromise( + { path: reference.path, operation: FirestoreOperation.UPDATE }, + () => { + const dataReader = newUserDataReader(firestore); - const dataReader = newUserDataReader(firestore); - - // For Compat types, we have to "extract" the underlying types before - // performing validation. - fieldOrUpdateData = getModularInstance(fieldOrUpdateData); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); - let parsed: ParsedUpdateData; - if ( - typeof fieldOrUpdateData === 'string' || - fieldOrUpdateData instanceof FieldPath - ) { - parsed = parseUpdateVarargs( - dataReader, - 'updateDoc', - reference._key, - fieldOrUpdateData, - value, - moreFieldsAndValues - ); - } else { - parsed = parseUpdateData( - dataReader, - 'updateDoc', - reference._key, - fieldOrUpdateData - ); - } + let parsed: ParsedUpdateData; + if ( + typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath + ) { + parsed = parseUpdateVarargs( + dataReader, + 'updateDoc', + reference._key, + fieldOrUpdateData, + value, + moreFieldsAndValues + ); + } else { + parsed = parseUpdateData( + dataReader, + 'updateDoc', + reference._key, + fieldOrUpdateData + ); + } - const mutation = parsed.toMutation(reference._key, Precondition.exists(true)); - return executeWrite(firestore, [mutation]); + const mutation = parsed.toMutation( + reference._key, + Precondition.exists(true) + ); + return executeWrite(firestore, [mutation]); + } + ); } /** @@ -507,9 +575,20 @@ export function updateDoc( export function deleteDoc( reference: DocumentReference ): Promise { + reference = cast>( + reference, + DocumentReference + ); const firestore = cast(reference.firestore, Firestore); - const mutations = [new DeleteMutation(reference._key, Precondition.none())]; - return executeWrite(firestore, mutations); + return withContextPromise( + { path: reference.path, operation: FirestoreOperation.DELETE }, + () => { + const mutations = [ + new DeleteMutation(reference._key, Precondition.none()) + ]; + return executeWrite(firestore, mutations); + } + ); } /** @@ -541,23 +620,38 @@ export function addDoc( reference: CollectionReference, data: WithFieldValue ): Promise> { + reference = cast>( + reference, + CollectionReference + ); const firestore = cast(reference.firestore, Firestore); const docRef = doc(reference); - const convertedValue = applyFirestoreDataConverter(reference.converter, data); + return withContextPromise( + { path: docRef.path, operation: FirestoreOperation.WRITE }, + () => { + const convertedValue = applyFirestoreDataConverter( + reference.converter, + data + ); - const dataReader = newUserDataReader(reference.firestore); - const parsed = parseSetData( - dataReader, - 'addDoc', - docRef._key, - convertedValue, - reference.converter !== null, - {} - ); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData( + dataReader, + 'addDoc', + docRef._key, + convertedValue, + reference.converter !== null, + {} + ); - const mutation = parsed.toMutation(docRef._key, Precondition.exists(false)); - return executeWrite(firestore, [mutation]).then(() => docRef); + const mutation = parsed.toMutation( + docRef._key, + Precondition.exists(false) + ); + return executeWrite(firestore, [mutation]).then(() => docRef); + } + ); } /** @@ -776,10 +870,15 @@ export function onSnapshot( let observer: PartialObserver; let firestore: Firestore; let internalQuery: InternalQuery; + let errorContext: FirestoreErrorContext; if (reference instanceof DocumentReference) { firestore = cast(reference.firestore, Firestore); internalQuery = newQueryForPath(reference._key.path); + errorContext = { + path: reference.path, + operation: FirestoreOperation.READ + }; observer = { next: snapshot => { @@ -802,6 +901,10 @@ export function onSnapshot( const query = cast>(reference, Query); firestore = cast(query.firestore, Firestore); internalQuery = query._query; + errorContext = { + path: queryErrorPath(query._query), + operation: FirestoreOperation.LIST + }; const userDataWriter = new ExpUserDataWriter(firestore); observer = { next: snapshot => { @@ -815,16 +918,21 @@ export function onSnapshot( complete: args[currArg + 2] as CompleteFn }; - validateHasExplicitOrderByForLimitToLast(reference._query); + withContextSync(errorContext, () => + validateHasExplicitOrderByForLimitToLast(query._query) + ); } - const client = ensureFirestoreConfigured(firestore); - return firestoreClientListen( - client, - internalQuery, - internalOptions, - observer - ); + return withContextSync(errorContext, () => { + const client = ensureFirestoreConfigured(firestore); + return firestoreClientListen( + client, + internalQuery, + internalOptions, + observer, + errorContext + ); + }); } /** @@ -1379,7 +1487,12 @@ function onSnapshotDocumentSnapshotBundle< }) .catch(e => { if (observer.error) { - observer.error(e); + observer.error( + withContext(e, { + path: json.bundleName, + operation: FirestoreOperation.READ + }) as FirestoreError + ); } return () => {}; }); @@ -1443,7 +1556,11 @@ function onSnapshotQuerySnapshotBundle< }) .catch(e => { if (observer.error) { - observer.error(e); + observer.error( + withContext(e, { + operation: FirestoreOperation.LIST + }) as FirestoreError + ); } return () => {}; }); diff --git a/packages/firestore/src/core/firestore_client.ts b/packages/firestore/src/core/firestore_client.ts index d843bc168f..cf4feb151c 100644 --- a/packages/firestore/src/core/firestore_client.ts +++ b/packages/firestore/src/core/firestore_client.ts @@ -62,7 +62,7 @@ import { AsyncQueue, wrapInUserErrorIfRecoverable } from '../util/async_queue'; import { BundleReader, BundleReaderSync } from '../util/bundle_reader'; import { newBundleReader } from '../util/bundle_reader_impl'; import { newBundleReaderSync } from '../util/bundle_reader_sync_impl'; -import { Code, FirestoreError } from '../util/error'; +import { Code, FirestoreError, FirestoreErrorContext } from '../util/error'; import { logDebug, logWarn } from '../util/log'; import { AutoId } from '../util/misc'; import { Deferred } from '../util/promise'; @@ -458,9 +458,10 @@ export function firestoreClientListen( client: FirestoreClient, query: QueryOrPipeline, options: ListenOptions, - observer: Partial> + observer: Partial>, + errorContext?: FirestoreErrorContext ): () => void { - const wrappedObserver = new AsyncObserver(observer); + const wrappedObserver = new AsyncObserver(observer, errorContext); const listener = new QueryListener(query, wrappedObserver, options); client.asyncQueue.enqueueAndForget(async () => { const eventManager = await getEventManager(client); diff --git a/packages/firestore/src/core/query.ts b/packages/firestore/src/core/query.ts index ca875bbb14..fbe8ebfff2 100644 --- a/packages/firestore/src/core/query.ts +++ b/packages/firestore/src/core/query.ts @@ -215,6 +215,16 @@ export function isCollectionGroupQuery(query: Query): boolean { return query.collectionGroup !== null; } +/** + * Returns the path or collection group ID targeted by this query for error + * context reporting. + */ +export function queryErrorPath(query: Query): string { + return query.collectionGroup !== null + ? query.collectionGroup + : query.path.canonicalString(); +} + /** * Returns the normalized order-by constraint that is used to execute the Query, * which can be different from the order-by constraints the user provided (e.g. diff --git a/packages/firestore/src/core/transaction.ts b/packages/firestore/src/core/transaction.ts index d3dc6ee8a8..1b80067335 100644 --- a/packages/firestore/src/core/transaction.ts +++ b/packages/firestore/src/core/transaction.ts @@ -20,6 +20,7 @@ import { Document } from '../model/document'; import { DocumentKey } from '../model/document_key'; import { DeleteMutation, + getMutationsErrorContext, Mutation, Precondition, VerifyMutation @@ -30,7 +31,12 @@ import { invokeCommitRpc } from '../remote/datastore'; import { fail, debugAssert } from '../util/assert'; -import { Code, FirestoreError } from '../util/error'; +import { + Code, + FirestoreError, + FirestoreOperation, + withContext +} from '../util/error'; import { SnapshotVersion } from './snapshot_version'; @@ -84,7 +90,10 @@ export class Transaction { try { this.write(data.toMutation(key, this.preconditionForUpdate(key))); } catch (e) { - this.lastTransactionError = e as FirestoreError | null; + this.lastTransactionError = withContext(e, { + path: key.path.canonicalString(), + operation: FirestoreOperation.UPDATE + }) as FirestoreError | null; } this.writtenDocs.add(key.toString()); } @@ -111,7 +120,11 @@ export class Transaction { const key = DocumentKey.fromPath(path); this.mutations.push(new VerifyMutation(key, this.precondition(key))); }); - await invokeCommitRpc(this.datastore, this.mutations); + try { + await invokeCommitRpc(this.datastore, this.mutations); + } catch (e) { + throw withContext(e, getMutationsErrorContext(this.mutations)); + } this.committed = true; } diff --git a/packages/firestore/src/lite-api/aggregate.ts b/packages/firestore/src/lite-api/aggregate.ts index c1cc173f61..53ea8870be 100644 --- a/packages/firestore/src/lite-api/aggregate.ts +++ b/packages/firestore/src/lite-api/aggregate.ts @@ -18,8 +18,10 @@ import { deepEqual } from '@firebase/util'; import { AggregateImpl } from '../core/aggregate'; +import { queryErrorPath } from '../core/query'; import { ApiClientObjectMap, Value } from '../protos/firestore_proto_api'; import { invokeRunAggregationQueryRpc } from '../remote/datastore'; +import { FirestoreOperation, withContextPromise } from '../util/error'; import { cast } from '../util/input_validation'; import { mapToArray } from '../util/obj'; @@ -102,23 +104,31 @@ export function getAggregate< AggregateQuerySnapshot > { const firestore = cast(query.firestore, Firestore); - const datastore = getDatastore(firestore); + return withContextPromise( + { path: queryErrorPath(query._query), operation: FirestoreOperation.LIST }, + () => { + const datastore = getDatastore(firestore); - const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => { - return new AggregateImpl( - alias, - aggregate.aggregateType, - aggregate._internalFieldPath - ); - }); + const internalAggregates = mapToArray( + aggregateSpec, + (aggregate, alias) => { + return new AggregateImpl( + alias, + aggregate.aggregateType, + aggregate._internalFieldPath + ); + } + ); - // Run the aggregation and convert the results - return invokeRunAggregationQueryRpc( - datastore, - query._query, - internalAggregates - ).then(aggregateResult => - convertToAggregateQuerySnapshot(firestore, query, aggregateResult) + // Run the aggregation and convert the results + return invokeRunAggregationQueryRpc( + datastore, + query._query, + internalAggregates + ).then(aggregateResult => + convertToAggregateQuerySnapshot(firestore, query, aggregateResult) + ); + } ); } diff --git a/packages/firestore/src/lite-api/pipeline_impl.ts b/packages/firestore/src/lite-api/pipeline_impl.ts index 7a8a1991cf..3762be9a95 100644 --- a/packages/firestore/src/lite-api/pipeline_impl.ts +++ b/packages/firestore/src/lite-api/pipeline_impl.ts @@ -20,7 +20,7 @@ import { StructuredPipelineOptions } from '../core/structured_pipeline'; import { invokeExecutePipeline } from '../remote/datastore'; -import { Code, FirestoreError } from '../util/error'; +import { Code, FirestoreError, withContextPromise } from '../util/error'; import { cast } from '../util/input_validation'; import { getDatastore } from './components'; @@ -31,7 +31,7 @@ import { PipelineSource } from './pipeline-source'; import { PipelineExecuteOptions } from './pipeline_options'; import { DocumentReference } from './reference'; import { LiteUserDataWriter } from './reference_impl'; -import { Stage } from './stage'; +import { getPipelineErrorContext, Stage } from './stage'; import { newUserDataReader, UserDataSource } from './user_data_reader'; declare module './database' { @@ -133,40 +133,43 @@ export function execute( }; const { pipeline, rawOptions, atomic, ...rest } = options; + const errorContext = getPipelineErrorContext(pipeline.stages); - if (!pipeline._db) { - return Promise.reject( - new FirestoreError( - Code.FAILED_PRECONDITION, - 'This pipeline was created without a database (e.g., as a subcollection pipeline) and cannot be executed directly. It can only be used as part of another pipeline.' - ) - ); - } - const datastore = getDatastore(pipeline._db); - const firestore = cast(pipeline._db, Firestore); + return withContextPromise(errorContext, () => { + if (!pipeline._db) { + return Promise.reject( + new FirestoreError( + Code.FAILED_PRECONDITION, + 'This pipeline was created without a database (e.g., as a subcollection pipeline) and cannot be executed directly. It can only be used as part of another pipeline.' + ) + ); + } + const datastore = getDatastore(pipeline._db); + const firestore = cast(pipeline._db, Firestore); - const userDataReader = newUserDataReader(firestore); - const context = userDataReader.createContext( - UserDataSource.Argument, - 'execute' - ); + const userDataReader = newUserDataReader(firestore); + const context = userDataReader.createContext( + UserDataSource.Argument, + 'execute' + ); - pipeline._readUserData(context); - const userDataWriter = new LiteUserDataWriter(firestore); + pipeline._readUserData(context); + const userDataWriter = new LiteUserDataWriter(firestore); - const structuredPipelineOptions = new StructuredPipelineOptions( - rest, - rawOptions - ); - structuredPipelineOptions._readUserData(context); + const structuredPipelineOptions = new StructuredPipelineOptions( + rest, + rawOptions + ); + structuredPipelineOptions._readUserData(context); - const structuredPipeline: StructuredPipeline = new StructuredPipeline( - pipeline, - structuredPipelineOptions - ); + const structuredPipeline: StructuredPipeline = new StructuredPipeline( + pipeline, + structuredPipelineOptions + ); - return invokeExecutePipeline(datastore, structuredPipeline, { atomic }).then( - result => { + return invokeExecutePipeline(datastore, structuredPipeline, { + atomic + }).then(result => { // Get the execution time from the first result. // firestoreClientExecutePipeline returns at least one PipelineStreamElement // even if the returned document set is empty. @@ -191,8 +194,8 @@ export function execute( ); return new PipelineSnapshot(pipeline, docs, executionTime); - } - ); + }); + }); } /** diff --git a/packages/firestore/src/lite-api/reference_impl.ts b/packages/firestore/src/lite-api/reference_impl.ts index 6d92ccab47..03f483f3ec 100644 --- a/packages/firestore/src/lite-api/reference_impl.ts +++ b/packages/firestore/src/lite-api/reference_impl.ts @@ -21,7 +21,7 @@ import { } from '@firebase/firestore-types'; import { getModularInstance } from '@firebase/util'; -import { LimitType } from '../core/query'; +import { LimitType, queryErrorPath } from '../core/query'; import { DeleteMutation, Precondition } from '../model/mutation'; import { invokeBatchGetDocumentsRpc, @@ -30,6 +30,7 @@ import { } from '../remote/datastore'; import { hardAssert } from '../util/assert'; import { ByteString } from '../util/byte_string'; +import { FirestoreOperation, withContextPromise } from '../util/error'; import { cast } from '../util/input_validation'; import { Bytes } from './bytes'; @@ -128,23 +129,28 @@ export function getDoc( reference, DocumentReference ); - const datastore = getDatastore(reference.firestore); - const userDataWriter = new LiteUserDataWriter(reference.firestore); + return withContextPromise( + { path: reference.path, operation: FirestoreOperation.READ }, + () => { + const datastore = getDatastore(reference.firestore); + const userDataWriter = new LiteUserDataWriter(reference.firestore); - return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then( - result => { - hardAssert( - result.length === 1, - 0x3d02, - 'Expected a single document result' - ); - const document = result[0]; - return new DocumentSnapshot( - reference.firestore, - userDataWriter, - reference._key, - document.isFoundDocument() ? document : null, - reference.converter + return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then( + result => { + hardAssert( + result.length === 1, + 0x3d02, + 'Expected a single document result' + ); + const document = result[0]; + return new DocumentSnapshot( + reference.firestore, + userDataWriter, + reference._key, + document.isFoundDocument() ? document : null, + reference.converter + ); + } ); } ); @@ -166,31 +172,36 @@ export function getDocs( query: Query ): Promise> { query = cast>(query, Query); - validateHasExplicitOrderByForLimitToLast(query._query); + return withContextPromise( + { path: queryErrorPath(query._query), operation: FirestoreOperation.LIST }, + () => { + validateHasExplicitOrderByForLimitToLast(query._query); - const datastore = getDatastore(query.firestore); - const userDataWriter = new LiteUserDataWriter(query.firestore); - return invokeRunQueryRpc(datastore, query._query).then(result => { - const docs = result.map( - doc => - new QueryDocumentSnapshot( - query.firestore, - userDataWriter, - doc.key, - doc, - query.converter - ) - ); + const datastore = getDatastore(query.firestore); + const userDataWriter = new LiteUserDataWriter(query.firestore); + return invokeRunQueryRpc(datastore, query._query).then(result => { + const docs = result.map( + doc => + new QueryDocumentSnapshot( + query.firestore, + userDataWriter, + doc.key, + doc, + query.converter + ) + ); - if (query._query.limitType === LimitType.Last) { - // Limit to last queries reverse the orderBy constraint that was - // specified by the user. As such, we need to reverse the order of the - // results to return the documents in the expected order. - docs.reverse(); - } + if (query._query.limitType === LimitType.Last) { + // Limit to last queries reverse the orderBy constraint that was + // specified by the user. As such, we need to reverse the order of the + // results to return the documents in the expected order. + docs.reverse(); + } - return new QuerySnapshot(query, docs); - }); + return new QuerySnapshot(query, docs); + }); + } + ); } /** @@ -243,25 +254,30 @@ export function setDoc( reference, DocumentReference ); - const convertedValue = applyFirestoreDataConverter( - reference.converter, - data, - options - ); - const dataReader = newUserDataReader(reference.firestore); - const parsed = parseSetData( - dataReader, - 'setDoc', - reference._key, - convertedValue, - reference.converter !== null, - options - ); + return withContextPromise( + { path: reference.path, operation: FirestoreOperation.WRITE }, + () => { + const convertedValue = applyFirestoreDataConverter( + reference.converter, + data, + options + ); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData( + dataReader, + 'setDoc', + reference._key, + convertedValue, + reference.converter !== null, + options + ); - const datastore = getDatastore(reference.firestore); - return invokeCommitRpc(datastore, [ - parsed.toMutation(reference._key, Precondition.none()) - ]); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(reference._key, Precondition.none()) + ]); + } + ); } /** @@ -323,38 +339,43 @@ export function updateDoc( reference, DocumentReference ); - const dataReader = newUserDataReader(reference.firestore); + return withContextPromise( + { path: reference.path, operation: FirestoreOperation.UPDATE }, + () => { + const dataReader = newUserDataReader(reference.firestore); - // For Compat types, we have to "extract" the underlying types before - // performing validation. - fieldOrUpdateData = getModularInstance(fieldOrUpdateData); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); - let parsed: ParsedUpdateData; - if ( - typeof fieldOrUpdateData === 'string' || - fieldOrUpdateData instanceof FieldPath - ) { - parsed = parseUpdateVarargs( - dataReader, - 'updateDoc', - reference._key, - fieldOrUpdateData, - value, - moreFieldsAndValues - ); - } else { - parsed = parseUpdateData( - dataReader, - 'updateDoc', - reference._key, - fieldOrUpdateData - ); - } + let parsed: ParsedUpdateData; + if ( + typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath + ) { + parsed = parseUpdateVarargs( + dataReader, + 'updateDoc', + reference._key, + fieldOrUpdateData, + value, + moreFieldsAndValues + ); + } else { + parsed = parseUpdateData( + dataReader, + 'updateDoc', + reference._key, + fieldOrUpdateData + ); + } - const datastore = getDatastore(reference.firestore); - return invokeCommitRpc(datastore, [ - parsed.toMutation(reference._key, Precondition.exists(true)) - ]); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(reference._key, Precondition.exists(true)) + ]); + } + ); } /** @@ -376,10 +397,15 @@ export function deleteDoc( reference, DocumentReference ); - const datastore = getDatastore(reference.firestore); - return invokeCommitRpc(datastore, [ - new DeleteMutation(reference._key, Precondition.none()) - ]); + return withContextPromise( + { path: reference.path, operation: FirestoreOperation.DELETE }, + () => { + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + new DeleteMutation(reference._key, Precondition.none()) + ]); + } + ); } /** @@ -406,24 +432,28 @@ export function addDoc( CollectionReference ); const docRef = doc(reference); + return withContextPromise( + { path: docRef.path, operation: FirestoreOperation.WRITE }, + () => { + const convertedValue = applyFirestoreDataConverter( + reference.converter, + data as PartialWithFieldValue + ); - const convertedValue = applyFirestoreDataConverter( - reference.converter, - data as PartialWithFieldValue - ); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData( + dataReader, + 'addDoc', + docRef._key, + convertedValue, + docRef.converter !== null, + {} + ); - const dataReader = newUserDataReader(reference.firestore); - const parsed = parseSetData( - dataReader, - 'addDoc', - docRef._key, - convertedValue, - docRef.converter !== null, - {} + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(docRef._key, Precondition.exists(false)) + ]).then(() => docRef); + } ); - - const datastore = getDatastore(reference.firestore); - return invokeCommitRpc(datastore, [ - parsed.toMutation(docRef._key, Precondition.exists(false)) - ]).then(() => docRef); } diff --git a/packages/firestore/src/lite-api/stage.ts b/packages/firestore/src/lite-api/stage.ts index af478333fd..1bab5b9d72 100644 --- a/packages/firestore/src/lite-api/stage.ts +++ b/packages/firestore/src/lite-api/stage.ts @@ -32,7 +32,12 @@ import { toStringValue } from '../remote/serializer'; import { hardAssert } from '../util/assert'; -import { Code, FirestoreError } from '../util/error'; +import { + Code, + FirestoreError, + FirestoreErrorContext, + FirestoreOperation +} from '../util/error'; import { isPlainObject, validateNonEmptyArgument @@ -1256,3 +1261,38 @@ function readUserDataHelper< } return expressionMap; } + +/** + * Computes error context for a pipeline based on its source and mutation stages. + */ +export function getPipelineErrorContext( + stages: Stage[] +): FirestoreErrorContext { + let path: string | undefined; + const firstStage = stages[0]; + if (firstStage instanceof CollectionSource) { + path = firstStage.formattedCollectionPath.replace(/^\//, ''); + } else if (firstStage instanceof CollectionGroupSource) { + path = firstStage.collectionId; + } else if ( + firstStage instanceof DocumentsSource && + firstStage.formattedPaths.length === 1 + ) { + path = firstStage.formattedPaths[0].replace(/^\//, ''); + } + + let operation: FirestoreOperation; + if (stages.some(s => s instanceof Delete)) { + operation = FirestoreOperation.DELETE; + } else if (stages.some(s => s instanceof Update)) { + operation = FirestoreOperation.UPDATE; + } else if (stages.some(s => s instanceof Insert || s instanceof Upsert)) { + operation = FirestoreOperation.WRITE; + } else if (firstStage instanceof DocumentsSource) { + operation = FirestoreOperation.READ; + } else { + operation = FirestoreOperation.LIST; + } + + return path !== undefined ? { path, operation } : { operation }; +} diff --git a/packages/firestore/src/lite-api/transaction.ts b/packages/firestore/src/lite-api/transaction.ts index 9a405feebe..75cd7d691e 100644 --- a/packages/firestore/src/lite-api/transaction.ts +++ b/packages/firestore/src/lite-api/transaction.ts @@ -26,6 +26,11 @@ import { import { TransactionRunner } from '../core/transaction_runner'; import { fail } from '../util/assert'; import { newAsyncQueue } from '../util/async_queue_impl'; +import { + FirestoreOperation, + withContextPromise, + withContextSync +} from '../util/error'; import { cast } from '../util/input_validation'; import { Deferred } from '../util/promise'; @@ -92,37 +97,44 @@ export class Transaction { ): Promise> { const ref = validateReference(documentRef, this._firestore); const userDataWriter = new LiteUserDataWriter(this._firestore); - return this._transaction.lookup([ref._key]).then(docs => { - if (!docs || docs.length !== 1) { - return fail(0x5de9, 'Mismatch in docs returned from document lookup.'); - } - const doc = docs[0]; - if (doc.isFoundDocument()) { - return new DocumentSnapshot( - this._firestore, - userDataWriter, - doc.key, - doc, - ref.converter - ); - } else if (doc.isNoDocument()) { - return new DocumentSnapshot( - this._firestore, - userDataWriter, - ref._key, - null, - ref.converter - ); - } else { - throw fail( - 0x4801, - 'BatchGetDocumentsRequest returned unexpected document', - { - doc + return withContextPromise( + { path: ref.path, operation: FirestoreOperation.READ }, + () => + this._transaction.lookup([ref._key]).then(docs => { + if (!docs || docs.length !== 1) { + return fail( + 0x5de9, + 'Mismatch in docs returned from document lookup.' + ); } - ); - } - }); + const doc = docs[0]; + if (doc.isFoundDocument()) { + return new DocumentSnapshot( + this._firestore, + userDataWriter, + doc.key, + doc, + ref.converter + ); + } else if (doc.isNoDocument()) { + return new DocumentSnapshot( + this._firestore, + userDataWriter, + ref._key, + null, + ref.converter + ); + } else { + throw fail( + 0x4801, + 'BatchGetDocumentsRequest returned unexpected document', + { + doc + } + ); + } + }) + ); } /** @@ -161,21 +173,26 @@ export class Transaction { options?: SetOptions ): this { const ref = validateReference(documentRef, this._firestore); - const convertedValue = applyFirestoreDataConverter( - ref.converter, - value, - options - ); - const parsed = parseSetData( - this._dataReader, - 'Transaction.set', - ref._key, - convertedValue, - ref.converter !== null, - options + return withContextSync( + { path: ref.path, operation: FirestoreOperation.WRITE }, + () => { + const convertedValue = applyFirestoreDataConverter( + ref.converter, + value, + options + ); + const parsed = parseSetData( + this._dataReader, + 'Transaction.set', + ref._key, + convertedValue, + ref.converter !== null, + options + ); + this._transaction.set(ref._key, parsed); + return this; + } ); - this._transaction.set(ref._key, parsed); - return this; } /** @@ -222,35 +239,39 @@ export class Transaction { ...moreFieldsAndValues: unknown[] ): this { const ref = validateReference(documentRef, this._firestore); + return withContextSync( + { path: ref.path, operation: FirestoreOperation.UPDATE }, + () => { + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); - // For Compat types, we have to "extract" the underlying types before - // performing validation. - fieldOrUpdateData = getModularInstance(fieldOrUpdateData); - - let parsed; - if ( - typeof fieldOrUpdateData === 'string' || - fieldOrUpdateData instanceof FieldPath - ) { - parsed = parseUpdateVarargs( - this._dataReader, - 'Transaction.update', - ref._key, - fieldOrUpdateData, - value, - moreFieldsAndValues - ); - } else { - parsed = parseUpdateData( - this._dataReader, - 'Transaction.update', - ref._key, - fieldOrUpdateData - ); - } + let parsed; + if ( + typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath + ) { + parsed = parseUpdateVarargs( + this._dataReader, + 'Transaction.update', + ref._key, + fieldOrUpdateData, + value, + moreFieldsAndValues + ); + } else { + parsed = parseUpdateData( + this._dataReader, + 'Transaction.update', + ref._key, + fieldOrUpdateData + ); + } - this._transaction.update(ref._key, parsed); - return this; + this._transaction.update(ref._key, parsed); + return this; + } + ); } /** @@ -263,8 +284,13 @@ export class Transaction { documentRef: DocumentReference ): this { const ref = validateReference(documentRef, this._firestore); - this._transaction.delete(ref._key); - return this; + return withContextSync( + { path: ref.path, operation: FirestoreOperation.DELETE }, + () => { + this._transaction.delete(ref._key); + return this; + } + ); } } diff --git a/packages/firestore/src/lite-api/write_batch.ts b/packages/firestore/src/lite-api/write_batch.ts index 4c2252d1b2..4f131230cc 100644 --- a/packages/firestore/src/lite-api/write_batch.ts +++ b/packages/firestore/src/lite-api/write_batch.ts @@ -17,9 +17,20 @@ import { Compat, getModularInstance } from '@firebase/util'; -import { DeleteMutation, Mutation, Precondition } from '../model/mutation'; +import { + DeleteMutation, + getMutationsErrorContext, + Mutation, + Precondition +} from '../model/mutation'; import { invokeCommitRpc } from '../remote/datastore'; -import { Code, FirestoreError } from '../util/error'; +import { + Code, + FirestoreError, + FirestoreOperation, + withContextPromise, + withContextSync +} from '../util/error'; import { cast } from '../util/input_validation'; import { getDatastore } from './components'; @@ -100,24 +111,30 @@ export class WriteBatch { data: WithFieldValue | PartialWithFieldValue, options?: SetOptions ): WriteBatch { - this._verifyNotCommitted(); - const ref = validateReference(documentRef, this._firestore); - - const convertedValue = applyFirestoreDataConverter( - ref.converter, - data, - options + withContextSync({ operation: FirestoreOperation.WRITE }, () => + this._verifyNotCommitted() ); - const parsed = parseSetData( - this._dataReader, - 'WriteBatch.set', - ref._key, - convertedValue, - ref.converter !== null, - options + const ref = validateReference(documentRef, this._firestore); + return withContextSync( + { path: ref.path, operation: FirestoreOperation.WRITE }, + () => { + const convertedValue = applyFirestoreDataConverter( + ref.converter, + data, + options + ); + const parsed = parseSetData( + this._dataReader, + 'WriteBatch.set', + ref._key, + convertedValue, + ref.converter !== null, + options + ); + this._mutations.push(parsed.toMutation(ref._key, Precondition.none())); + return this; + } ); - this._mutations.push(parsed.toMutation(ref._key, Precondition.none())); - return this; } /** @@ -163,39 +180,45 @@ export class WriteBatch { value?: unknown, ...moreFieldsAndValues: unknown[] ): WriteBatch { - this._verifyNotCommitted(); + withContextSync({ operation: FirestoreOperation.UPDATE }, () => + this._verifyNotCommitted() + ); const ref = validateReference(documentRef, this._firestore); + return withContextSync( + { path: ref.path, operation: FirestoreOperation.UPDATE }, + () => { + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); - // For Compat types, we have to "extract" the underlying types before - // performing validation. - fieldOrUpdateData = getModularInstance(fieldOrUpdateData); + let parsed; + if ( + typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath + ) { + parsed = parseUpdateVarargs( + this._dataReader, + 'WriteBatch.update', + ref._key, + fieldOrUpdateData, + value, + moreFieldsAndValues + ); + } else { + parsed = parseUpdateData( + this._dataReader, + 'WriteBatch.update', + ref._key, + fieldOrUpdateData + ); + } - let parsed; - if ( - typeof fieldOrUpdateData === 'string' || - fieldOrUpdateData instanceof FieldPath - ) { - parsed = parseUpdateVarargs( - this._dataReader, - 'WriteBatch.update', - ref._key, - fieldOrUpdateData, - value, - moreFieldsAndValues - ); - } else { - parsed = parseUpdateData( - this._dataReader, - 'WriteBatch.update', - ref._key, - fieldOrUpdateData - ); - } - - this._mutations.push( - parsed.toMutation(ref._key, Precondition.exists(true)) + this._mutations.push( + parsed.toMutation(ref._key, Precondition.exists(true)) + ); + return this; + } ); - return this; } /** @@ -207,7 +230,9 @@ export class WriteBatch { delete( documentRef: DocumentReference ): WriteBatch { - this._verifyNotCommitted(); + withContextSync({ operation: FirestoreOperation.DELETE }, () => + this._verifyNotCommitted() + ); const ref = validateReference(documentRef, this._firestore); this._mutations = this._mutations.concat( new DeleteMutation(ref._key, Precondition.none()) @@ -228,13 +253,15 @@ export class WriteBatch { * resolve while you're offline). */ commit(): Promise { - this._verifyNotCommitted(); - this._committed = true; - if (this._mutations.length > 0) { - return this._commitHandler(this._mutations); - } + return withContextPromise(getMutationsErrorContext(this._mutations), () => { + this._verifyNotCommitted(); + this._committed = true; + if (this._mutations.length > 0) { + return this._commitHandler(this._mutations); + } - return Promise.resolve(); + return Promise.resolve(); + }); } private _verifyNotCommitted(): void { diff --git a/packages/firestore/src/model/mutation.ts b/packages/firestore/src/model/mutation.ts index 8c3477c5c4..eca227bdb0 100644 --- a/packages/firestore/src/model/mutation.ts +++ b/packages/firestore/src/model/mutation.ts @@ -19,6 +19,7 @@ import { SnapshotVersion } from '../core/snapshot_version'; import { Timestamp } from '../lite-api/timestamp'; import { Value as ProtoValue } from '../protos/firestore_proto_api'; import { debugAssert, hardAssert } from '../util/assert'; +import { FirestoreErrorContext, FirestoreOperation } from '../util/error'; import { arrayEquals } from '../util/misc'; import { SortedSet } from '../util/sorted_set'; @@ -753,3 +754,49 @@ export class VerifyMutation extends Mutation { return null; } } + +/** + * Computes error context for a list of mutations (e.g. a WriteBatch or + * Transaction commit). Includes `path` when all relevant mutations target a + * single document. + */ +export function getMutationsErrorContext( + mutations: Mutation[] +): FirestoreErrorContext { + const writeMutations = mutations.filter(m => m.type !== MutationType.Verify); + const relevant = writeMutations.length > 0 ? writeMutations : mutations; + if (relevant.length === 0) { + return { operation: FirestoreOperation.WRITE }; + } + + const firstPath = relevant[0].key.path.canonicalString(); + const singlePath = relevant.every( + m => m.key.path.canonicalString() === firstPath + ) + ? firstPath + : undefined; + + let operation: FirestoreOperation; + if (writeMutations.length === 0) { + operation = FirestoreOperation.READ; + } else if (relevant.length === 1) { + switch (relevant[0].type) { + case MutationType.Delete: + operation = FirestoreOperation.DELETE; + break; + case MutationType.Patch: + operation = relevant[0].precondition.exists + ? FirestoreOperation.UPDATE + : FirestoreOperation.WRITE; + break; + default: + operation = FirestoreOperation.WRITE; + } + } else { + operation = FirestoreOperation.WRITE; + } + + return singlePath !== undefined + ? { path: singlePath, operation } + : { operation }; +} diff --git a/packages/firestore/src/util/async_observer.ts b/packages/firestore/src/util/async_observer.ts index 239d372ea0..220995b660 100644 --- a/packages/firestore/src/util/async_observer.ts +++ b/packages/firestore/src/util/async_observer.ts @@ -17,7 +17,7 @@ import { Observer } from '../core/event_manager'; -import { FirestoreError } from './error'; +import { FirestoreError, FirestoreErrorContext, withContext } from './error'; import { logError } from './log'; import { EventHandler } from './misc'; @@ -33,7 +33,10 @@ export class AsyncObserver implements Observer { */ private muted = false; - constructor(private observer: Partial>) {} + constructor( + private observer: Partial>, + private errorContext?: FirestoreErrorContext + ) {} next(value: T): void { if (this.muted) { @@ -48,6 +51,9 @@ export class AsyncObserver implements Observer { if (this.muted) { return; } + if (this.errorContext) { + error = withContext(error, this.errorContext); + } if (this.observer.error) { this.scheduleEvent(this.observer.error, error); } else { diff --git a/packages/firestore/src/util/error.ts b/packages/firestore/src/util/error.ts index 3b852ddfce..a7c06bf5a0 100644 --- a/packages/firestore/src/util/error.ts +++ b/packages/firestore/src/util/error.ts @@ -15,7 +15,7 @@ * limitations under the License. */ -import { FirebaseError } from '@firebase/util'; +import { FirebaseError, isContextualErrorsEnabled } from '@firebase/util'; /** * The set of Firestore status codes. The codes are the same at the ones @@ -209,8 +209,31 @@ export const Code = { DATA_LOSS: 'data-loss' as FirestoreErrorCode }; +/** + * The Firestore operation associated with a {@link FirestoreErrorContext}. + */ +export enum FirestoreOperation { + READ = 'read', + WRITE = 'write', + LIST = 'list', + UPDATE = 'update', + DELETE = 'delete' +} + +/** + * Contextual information attached to a {@link FirestoreError} when contextual + * errors are enabled. + */ +export interface FirestoreErrorContext { + path?: string; + operation?: FirestoreOperation; +} + /** An error returned by a Firestore operation. */ -export class FirestoreError extends FirebaseError { +export class FirestoreError extends FirebaseError { + /** A custom error description. */ + declare readonly message: string; + /** The stack of the error. */ readonly stack?: string; @@ -223,9 +246,10 @@ export class FirestoreError extends FirebaseError { /** * A custom error description. */ - readonly message: string + message: string, + context?: FirestoreErrorContext ) { - super(code, message); + super(code, message, undefined, context); // HACK: We write a toString property directly because Error is not a real // class and so inheritance does not work correctly. We could alternatively @@ -233,3 +257,53 @@ export class FirestoreError extends FirebaseError { this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; } } + +/** @internal */ +export function withContext( + e: FirestoreError, + context: FirestoreErrorContext +): FirestoreError; +/** @internal */ +export function withContext( + e: unknown, + context: FirestoreErrorContext +): unknown; +export function withContext( + e: unknown, + context: FirestoreErrorContext +): unknown { + if ( + !isContextualErrorsEnabled() || + !(e instanceof FirestoreError) || + e.context + ) { + return e; + } + return new FirestoreError(e.code, e.message, context); +} + +/** @internal */ +export function withContextSync( + context: FirestoreErrorContext, + fn: () => T +): T { + try { + return fn(); + } catch (e) { + throw withContext(e, context); + } +} + +/** @internal */ +export function withContextPromise( + context: FirestoreErrorContext, + fn: () => Promise +): Promise { + try { + return fn().catch(e => { + throw withContext(e, context); + }); + } catch (e) { + throw withContext(e, context); + } +} diff --git a/packages/firestore/src/util/log.ts b/packages/firestore/src/util/log.ts index cbdbad38ec..d64b77b448 100644 --- a/packages/firestore/src/util/log.ts +++ b/packages/firestore/src/util/log.ts @@ -23,12 +23,10 @@ import { formatJSON } from '../platform/format_json'; export { LogLevel, LogLevelString }; const logClient = new Logger('@firebase/firestore'); - // Helper methods are needed because variables can't be exported as read/write export function getLogLevel(): LogLevel { return logClient.logLevel; } - /** * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). * diff --git a/packages/firestore/test/unit/api/contextual_errors.test.ts b/packages/firestore/test/unit/api/contextual_errors.test.ts new file mode 100644 index 0000000000..5db8a58a60 --- /dev/null +++ b/packages/firestore/test/unit/api/contextual_errors.test.ts @@ -0,0 +1,599 @@ +/** + * @license + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { enableContextualErrors, FirebaseError } from '@firebase/util'; + +import { + addDoc, + collection, + collectionGroup, + count, + deleteDoc, + doc, + Firestore, + FirestoreError, + FirestoreOperation, + getAggregateFromServer, + getCountFromServer, + getDoc, + getDocFromCache, + getDocFromServer, + getDocs, + getDocsFromCache, + getDocsFromServer, + limitToLast, + onSnapshot, + query, + runTransaction, + setDoc, + updateDoc, + writeBatch +} from '../../../src'; +import { + EmptyAppCheckTokenProvider, + EmptyAuthCredentialsProvider +} from '../../../src/api/credentials'; +import { execute } from '../../../src/api/pipeline_impl'; +import { + MemoryOfflineComponentProvider, + OnlineComponentProvider +} from '../../../src/core/component_provider'; +import { DatabaseId } from '../../../src/core/database_info'; +import { getAggregate, getCount } from '../../../src/lite-api/aggregate'; +import { + getDatastore, + removeComponents +} from '../../../src/lite-api/components'; +import { Firestore as LiteFirestore } from '../../../src/lite-api/database'; +import { execute as liteExecute } from '../../../src/lite-api/pipeline_impl'; +import { + addDoc as liteAddDoc, + deleteDoc as liteDeleteDoc, + getDoc as liteGetDoc, + getDocs as liteGetDocs, + setDoc as liteSetDoc, + updateDoc as liteUpdateDoc +} from '../../../src/lite-api/reference_impl'; +import { runTransaction as liteRunTransaction } from '../../../src/lite-api/transaction'; +import { writeBatch as liteWriteBatch } from '../../../src/lite-api/write_batch'; +import { AsyncObserver } from '../../../src/util/async_observer'; +import { Code, withContext } from '../../../src/util/error'; +import { newTestFirestore } from '../../util/api_helpers'; + +function createFailingFirestore(error: FirestoreError): Firestore { + const db = newTestFirestore(); + db._componentsProvider = { + _offline: { + build: () => new MemoryOfflineComponentProvider() + }, + _online: { + build: () => { + const provider = new OnlineComponentProvider(); + const ogCreateDatastore = provider.createDatastore.bind(provider); + provider.createDatastore = config => { + const datastore = ogCreateDatastore(config); + // @ts-ignore + datastore.invokeRPC = vi.fn().mockRejectedValue(error); + // @ts-ignore + datastore.invokeStreamingRPC = vi.fn().mockRejectedValue(error); + return datastore; + }; + return provider; + } + } + }; + return db; +} + +function createFailingLiteFirestore(error: FirestoreError): LiteFirestore { + const db = new LiteFirestore( + new EmptyAuthCredentialsProvider(), + new EmptyAppCheckTokenProvider(), + new DatabaseId('test-project'), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + { name: 'test-app', options: { appId: 'app-id', apiKey: 'api-key' } } as any + ); + const datastore = getDatastore(db); + // @ts-ignore + datastore.invokeRPC = vi.fn().mockRejectedValue(error); + // @ts-ignore + datastore.invokeStreamingRPC = vi.fn().mockRejectedValue(error); + return db; +} + +async function expectFirestoreError( + action: () => Promise | unknown +): Promise { + try { + await action(); + } catch (e) { + expect(e).toBeInstanceOf(FirestoreError); + expect(e).toBeInstanceOf(FirebaseError); + return e as FirestoreError; + } + throw new Error('Expected action to throw a FirestoreError'); +} + +describe('Contextual errors in Firestore SDK', () => { + afterEach(() => { + enableContextualErrors(false); + }); + + describe('withContext()', () => { + it('returns original error when contextual errors are disabled', () => { + const err = new FirestoreError( + Code.PERMISSION_DENIED, + 'Missing or insufficient permissions.' + ); + const wrapped = withContext(err, { + path: 'users/alice', + operation: FirestoreOperation.READ + }); + expect(wrapped).toBe(err); + expect((wrapped as FirestoreError).context).toBeUndefined(); + expect((wrapped as FirestoreError).message).toBe( + 'Missing or insufficient permissions.' + ); + }); + + it('attaches context and formats message/toString once when enabled', () => { + enableContextualErrors(true); + const err = new FirestoreError( + Code.PERMISSION_DENIED, + 'Missing or insufficient permissions.' + ); + const ctx = { + path: 'users/alice', + operation: FirestoreOperation.READ + }; + const wrapped = withContext(err, ctx) as FirestoreError; + expect(wrapped).toBeInstanceOf(FirestoreError); + expect(wrapped).toBeInstanceOf(FirebaseError); + expect(wrapped.code).toBe(Code.PERMISSION_DENIED); + expect(wrapped.context).toEqual(ctx); + expect(wrapped.message).toBe( + `Missing or insufficient permissions. Context: ${JSON.stringify(ctx)}` + ); + expect(wrapped.toString()).toBe( + `FirebaseError: [code=permission-denied]: Missing or insufficient permissions. Context: ${JSON.stringify(ctx)}` + ); + }); + + it('does not overwrite existing context', () => { + enableContextualErrors(true); + const originalCtx = { + path: 'users/alice', + operation: FirestoreOperation.READ + }; + const err = new FirestoreError( + Code.PERMISSION_DENIED, + 'Denied', + originalCtx + ); + const wrapped = withContext(err, { + path: 'users/bob', + operation: FirestoreOperation.WRITE + }) as FirestoreError; + expect(wrapped).toBe(err); + expect(wrapped.context).toEqual(originalCtx); + }); + + it('passes non-FirestoreError values through unchanged', () => { + enableContextualErrors(true); + const plainErr = new Error('boom'); + expect( + withContext(plainErr, { + path: 'users/alice', + operation: FirestoreOperation.READ + }) + ).toBe(plainErr); + }); + }); + + describe('AsyncObserver error context', () => { + it('wraps error delivered to user error callback when enabled', async () => { + enableContextualErrors(true); + const received = await new Promise(resolve => { + const observer = new AsyncObserver( + { error: resolve }, + { path: 'users/alice', operation: FirestoreOperation.READ } + ); + observer.error( + new FirestoreError(Code.PERMISSION_DENIED, 'Permission denied') + ); + }); + expect(received.context).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.READ + }); + expect(received.message).toContain('"path":"users/alice"'); + }); + + it('wraps error logged when no user error callback is provided', () => { + enableContextualErrors(true); + const logSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + const observer = new AsyncObserver( + {}, + { path: 'users', operation: FirestoreOperation.LIST } + ); + observer.error( + new FirestoreError(Code.PERMISSION_DENIED, 'Permission denied') + ); + expect(logSpy).toHaveBeenCalledTimes(1); + const loggedText = logSpy.mock.calls[0].join(' '); + expect(loggedText).toContain('"path":"users"'); + expect(loggedText).toContain('"operation":"list"'); + } finally { + logSpy.mockRestore(); + } + }); + }); + + describe('Full SDK operations', () => { + it('attaches READ context to getDocFromCache errors', async () => { + enableContextualErrors(true); + const db = newTestFirestore(); + const err = await expectFirestoreError(() => + getDocFromCache(doc(db, 'users/alice')) + ); + expect(err.code).toBe(Code.UNAVAILABLE); + expect(err.context).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.READ + }); + }); + + it('does not attach context to getDocFromCache errors when disabled', async () => { + const db = newTestFirestore(); + const err = await expectFirestoreError(() => + getDocFromCache(doc(db, 'users/alice')) + ); + expect(err.code).toBe(Code.UNAVAILABLE); + expect(err.context).toBeUndefined(); + expect(err.message).not.toContain('Context:'); + }); + + it('attaches context on terminated client for getDoc, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, setDoc, updateDoc, deleteDoc, addDoc, and onSnapshot', async () => { + enableContextualErrors(true); + const db = newTestFirestore(); + // Terminate without using terminate(db) since mock Firestore has no FirebaseApp + await db._delete(); + + const docRef = doc(db, 'users/alice'); + const colRef = collection(db, 'users'); + const groupQuery = collectionGroup(db, 'comments'); + + expect( + (await expectFirestoreError(() => getDoc(docRef))).context + ).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.READ + }); + expect( + (await expectFirestoreError(() => getDocFromServer(docRef))).context + ).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.READ + }); + expect( + (await expectFirestoreError(() => getDocs(colRef))).context + ).toEqual({ + path: 'users', + operation: FirestoreOperation.LIST + }); + expect( + (await expectFirestoreError(() => getDocs(groupQuery))).context + ).toEqual({ + path: 'comments', + operation: FirestoreOperation.LIST + }); + expect( + (await expectFirestoreError(() => getDocsFromCache(colRef))).context + ).toEqual({ + path: 'users', + operation: FirestoreOperation.LIST + }); + expect( + (await expectFirestoreError(() => getDocsFromServer(colRef))).context + ).toEqual({ + path: 'users', + operation: FirestoreOperation.LIST + }); + expect( + (await expectFirestoreError(() => setDoc(docRef, { a: 1 }))).context + ).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.WRITE + }); + expect( + (await expectFirestoreError(() => updateDoc(docRef, { a: 2 }))).context + ).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.UPDATE + }); + expect( + (await expectFirestoreError(() => deleteDoc(docRef))).context + ).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.DELETE + }); + const addErr = await expectFirestoreError(() => addDoc(colRef, { a: 1 })); + expect(addErr.context?.operation).toBe(FirestoreOperation.WRITE); + expect(addErr.context?.path).toMatch(/^users\/[^/]+$/); + + const docSnapErr = await expectFirestoreError(() => + onSnapshot(docRef, () => {}) + ); + expect(docSnapErr.context).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.READ + }); + const querySnapErr = await expectFirestoreError(() => + onSnapshot(colRef, () => {}) + ); + expect(querySnapErr.context).toEqual({ + path: 'users', + operation: FirestoreOperation.LIST + }); + }); + + it('attaches LIST context to limitToLast validation errors in getDocs and onSnapshot', async () => { + enableContextualErrors(true); + const db = newTestFirestore(); + const q = query(collection(db, 'orders'), limitToLast(5)); + + expect((await expectFirestoreError(() => getDocs(q))).context).toEqual({ + path: 'orders', + operation: FirestoreOperation.LIST + }); + expect( + (await expectFirestoreError(() => onSnapshot(q, () => {}))).context + ).toEqual({ + path: 'orders', + operation: FirestoreOperation.LIST + }); + }); + + it('attaches LIST context to getAggregateFromServer and getCountFromServer errors', async () => { + enableContextualErrors(true); + const db = createFailingFirestore( + new FirestoreError(Code.PERMISSION_DENIED, 'Denied') + ); + + const aggErr = await expectFirestoreError(() => + getAggregateFromServer(collection(db, 'metrics'), { total: count() }) + ); + expect(aggErr.context).toEqual({ + path: 'metrics', + operation: FirestoreOperation.LIST + }); + + const countErr = await expectFirestoreError(() => + getCountFromServer(collectionGroup(db, 'events')) + ); + expect(countErr.context).toEqual({ + path: 'events', + operation: FirestoreOperation.LIST + }); + }); + + it('attaches context to pipeline execute() errors', async () => { + enableContextualErrors(true); + const db = createFailingFirestore( + new FirestoreError(Code.PERMISSION_DENIED, 'Denied') + ); + + const colErr = await expectFirestoreError(() => + execute(db.pipeline().collection('books')) + ); + expect(colErr.context).toEqual({ + path: 'books', + operation: FirestoreOperation.LIST + }); + + const groupErr = await expectFirestoreError(() => + execute(db.pipeline().collectionGroup('reviews')) + ); + expect(groupErr.context).toEqual({ + path: 'reviews', + operation: FirestoreOperation.LIST + }); + }); + + it('attaches READ context to Transaction.get() and commit context to runTransaction()', async () => { + enableContextualErrors(true); + const db = createFailingFirestore( + new FirestoreError(Code.PERMISSION_DENIED, 'Denied') + ); + + const readErr = await expectFirestoreError(() => + runTransaction(db, async tx => { + await tx.get(doc(db, 'accounts/1')); + }) + ); + expect(readErr.context).toEqual({ + path: 'accounts/1', + operation: FirestoreOperation.READ + }); + + const singleWriteErr = await expectFirestoreError(() => + runTransaction(db, async tx => { + tx.delete(doc(db, 'accounts/1')); + }) + ); + expect(singleWriteErr.context).toEqual({ + path: 'accounts/1', + operation: FirestoreOperation.DELETE + }); + + const multiWriteErr = await expectFirestoreError(() => + runTransaction(db, async tx => { + tx.set(doc(db, 'accounts/1'), { a: 1 }); + tx.set(doc(db, 'accounts/2'), { a: 2 }); + }) + ); + expect(multiWriteErr.context).toEqual({ + operation: FirestoreOperation.WRITE + }); + }); + + it('attaches context to WriteBatch sync validation errors', async () => { + enableContextualErrors(true); + const db = newTestFirestore(); + const batch = writeBatch(db); + await batch.commit(); + + expect( + ( + await expectFirestoreError(() => + batch.set(doc(db, 'users/1'), { a: 1 }) + ) + ).context + ).toEqual({ operation: FirestoreOperation.WRITE }); + expect( + ( + await expectFirestoreError(() => + batch.update(doc(db, 'users/1'), { a: 1 }) + ) + ).context + ).toEqual({ operation: FirestoreOperation.UPDATE }); + expect( + (await expectFirestoreError(() => batch.delete(doc(db, 'users/1')))) + .context + ).toEqual({ operation: FirestoreOperation.DELETE }); + }); + }); + + describe('Lite SDK operations', () => { + let liteDb: LiteFirestore; + + afterEach(() => { + if (liteDb) { + removeComponents(liteDb); + } + }); + + it('attaches context to lite getDoc, getDocs, setDoc, updateDoc, deleteDoc, addDoc, getAggregate, getCount, WriteBatch, Transaction, and execute', async () => { + enableContextualErrors(true); + liteDb = createFailingLiteFirestore( + new FirestoreError(Code.PERMISSION_DENIED, 'Denied') + ); + + const docRef = doc(liteDb, 'users/alice'); + const colRef = collection(liteDb, 'users'); + const groupRef = collectionGroup(liteDb, 'tags'); + + expect( + (await expectFirestoreError(() => liteGetDoc(docRef))).context + ).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.READ + }); + expect( + (await expectFirestoreError(() => liteGetDocs(colRef))).context + ).toEqual({ + path: 'users', + operation: FirestoreOperation.LIST + }); + expect( + (await expectFirestoreError(() => liteGetDocs(groupRef))).context + ).toEqual({ + path: 'tags', + operation: FirestoreOperation.LIST + }); + expect( + (await expectFirestoreError(() => liteSetDoc(docRef, { a: 1 }))).context + ).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.WRITE + }); + expect( + (await expectFirestoreError(() => liteUpdateDoc(docRef, { a: 2 }))) + .context + ).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.UPDATE + }); + expect( + (await expectFirestoreError(() => liteDeleteDoc(docRef))).context + ).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.DELETE + }); + + const addErr = await expectFirestoreError(() => + liteAddDoc(colRef, { a: 1 }) + ); + expect(addErr.context?.operation).toBe(FirestoreOperation.WRITE); + expect(addErr.context?.path).toMatch(/^users\/[^/]+$/); + + expect( + ( + await expectFirestoreError(() => + getAggregate(colRef, { total: count() }) + ) + ).context + ).toEqual({ + path: 'users', + operation: FirestoreOperation.LIST + }); + expect( + (await expectFirestoreError(() => getCount(groupRef))).context + ).toEqual({ + path: 'tags', + operation: FirestoreOperation.LIST + }); + + const singleBatch = liteWriteBatch(liteDb); + singleBatch.update(docRef, { a: 1 }); + expect( + (await expectFirestoreError(() => singleBatch.commit())).context + ).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.UPDATE + }); + + const multiBatch = liteWriteBatch(liteDb); + multiBatch.set(doc(liteDb, 'users/1'), { a: 1 }); + multiBatch.set(doc(liteDb, 'users/2'), { a: 2 }); + expect( + (await expectFirestoreError(() => multiBatch.commit())).context + ).toEqual({ + operation: FirestoreOperation.WRITE + }); + + const txErr = await expectFirestoreError(() => + liteRunTransaction(liteDb, async tx => { + await tx.get(docRef); + }) + ); + expect(txErr.context).toEqual({ + path: 'users/alice', + operation: FirestoreOperation.READ + }); + + const pipeErr = await expectFirestoreError(() => + liteExecute(liteDb.pipeline().collection('books')) + ); + expect(pipeErr.context).toEqual({ + path: 'books', + operation: FirestoreOperation.LIST + }); + }); + }); +}); diff --git a/packages/util/src/errors.ts b/packages/util/src/errors.ts index a6aeed3274..9d67b2d19d 100644 --- a/packages/util/src/errors.ts +++ b/packages/util/src/errors.ts @@ -68,27 +68,41 @@ export interface StringLike { export interface ErrorData { [key: string]: unknown; } +function formatMessageWithContext(message: string, context: unknown): string { + try { + return `${message} Context: ${JSON.stringify(context)}`; + } catch { + return message; + } +} // Based on code from: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types -export class FirebaseError extends Error { +export class FirebaseError extends Error { /** The custom name for all FirebaseErrors. */ readonly name: string = ERROR_NAME; + readonly context?: T; + constructor( /** The error code for this error. */ readonly code: string, message: string, /** Custom data for this error. */ - public customData?: Record + public customData?: Record, + _context?: T ) { - super(message); + const includeContext = contextualErrors && _context !== undefined; + super( + includeContext ? formatMessageWithContext(message, _context) : message + ); + if (includeContext) { + this.context = _context; + } // Fix For ES5 // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work - // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget - // which we can now use since we no longer target ES5. - Object.setPrototypeOf(this, FirebaseError.prototype); + Object.setPrototypeOf(this, new.target.prototype); // Maintains proper stack trace for where our error was thrown. // Only available on V8. @@ -154,3 +168,13 @@ function replaceTemplate(template: string, data: ErrorData): string { return template; } } + +let contextualErrors = false; + +export function enableContextualErrors(enableFlag: boolean): void { + contextualErrors = enableFlag; +} + +export function isContextualErrorsEnabled(): boolean { + return contextualErrors; +} diff --git a/packages/util/test/errors.test.ts b/packages/util/test/errors.test.ts index 1794ccb80d..e47c548f15 100644 --- a/packages/util/test/errors.test.ts +++ b/packages/util/test/errors.test.ts @@ -14,8 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { assert, describe, it } from 'vitest'; -import { ErrorFactory, ErrorMap, FirebaseError } from '../src/errors'; +import { afterEach, assert, describe, it } from 'vitest'; +import { + enableContextualErrors, + ErrorFactory, + ErrorMap, + FirebaseError, + isContextualErrorsEnabled +} from '../src/errors'; type ErrorCode = 'generic-error' | 'file-not-found' | 'anon-replace' | 'overwrite-field'; @@ -41,6 +47,10 @@ const ERROR_FACTORY = new ErrorFactory( ); describe('FirebaseError', () => { + afterEach(() => { + enableContextualErrors(false); + }); + it('creates an Error', () => { const e = ERROR_FACTORY.create('generic-error'); assert.instanceOf(e, Error); @@ -114,6 +124,37 @@ describe('FirebaseError', () => { assert.match((e as FirebaseError).stack!, /dummy2[\s\S]*?dummy1/); } }); + + it('omits context when contextual errors are disabled', () => { + assert.isFalse(isContextualErrorsEnabled()); + const e = new FirebaseError('test/code', 'Something failed', undefined, { + path: 'users/123' + }); + assert.isUndefined(e.context); + assert.equal(e.message, 'Something failed'); + }); + + it('includes context in message and property when contextual errors are enabled', () => { + enableContextualErrors(true); + assert.isTrue(isContextualErrorsEnabled()); + const ctx = { path: 'users/123', operation: 'read' }; + const e = new FirebaseError( + 'test/code', + 'Something failed', + undefined, + ctx + ); + assert.deepEqual(e.context, ctx); + assert.equal(e.message, `Something failed Context: ${JSON.stringify(ctx)}`); + }); + + it('preserves instanceof for subclasses', () => { + class CustomFirebaseError extends FirebaseError<{ path: string }> {} + const e = new CustomFirebaseError('custom/code', 'boom'); + assert.instanceOf(e, Error); + assert.instanceOf(e, FirebaseError); + assert.instanceOf(e, CustomFirebaseError); + }); }); function dummy1(): void {