From 51f097e73f99f62ba2c72dd34e058d5a932145a7 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 20 Jul 2022 14:20:23 +0200 Subject: [PATCH 01/46] Creating empty @kbn/core-saved-objects-common package --- package.json | 2 + packages/BUILD.bazel | 2 + .../core-saved-objects-common/BUILD.bazel | 126 ++++++++++++++++++ .../core-saved-objects-common/README.md | 3 + .../core-saved-objects-common/jest.config.js | 13 ++ .../core-saved-objects-common/package.json | 8 ++ .../core-saved-objects-common/src/index.ts | 11 ++ .../core-saved-objects-common/tsconfig.json | 19 +++ yarn.lock | 8 ++ 9 files changed, 192 insertions(+) create mode 100644 packages/core/saved-objects/core-saved-objects-common/BUILD.bazel create mode 100644 packages/core/saved-objects/core-saved-objects-common/README.md create mode 100644 packages/core/saved-objects/core-saved-objects-common/jest.config.js create mode 100644 packages/core/saved-objects/core-saved-objects-common/package.json create mode 100644 packages/core/saved-objects/core-saved-objects-common/src/index.ts create mode 100644 packages/core/saved-objects/core-saved-objects-common/tsconfig.json diff --git a/package.json b/package.json index f23ef1aa97723..04001b79ed03a 100644 --- a/package.json +++ b/package.json @@ -216,6 +216,7 @@ "@kbn/core-preboot-server": "link:bazel-bin/packages/core/preboot/core-preboot-server", "@kbn/core-preboot-server-internal": "link:bazel-bin/packages/core/preboot/core-preboot-server-internal", "@kbn/core-preboot-server-mocks": "link:bazel-bin/packages/core/preboot/core-preboot-server-mocks", + "@kbn/core-saved-objects-common": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-common", "@kbn/core-test-helpers-http-setup-browser": "link:bazel-bin/packages/core/test-helpers/core-test-helpers-http-setup-browser", "@kbn/core-theme-browser": "link:bazel-bin/packages/core/theme/core-theme-browser", "@kbn/core-theme-browser-internal": "link:bazel-bin/packages/core/theme/core-theme-browser-internal", @@ -811,6 +812,7 @@ "@types/kbn__core-preboot-server-internal": "link:bazel-bin/packages/core/preboot/core-preboot-server-internal/npm_module_types", "@types/kbn__core-preboot-server-mocks": "link:bazel-bin/packages/core/preboot/core-preboot-server-mocks/npm_module_types", "@types/kbn__core-public-internal-base": "link:bazel-bin/packages/core/public/internal-base/npm_module_types", + "@types/kbn__core-saved-objects-common": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-common/npm_module_types", "@types/kbn__core-server-internal-base": "link:bazel-bin/packages/core/server/internal-base/npm_module_types", "@types/kbn__core-test-helpers-http-setup-browser": "link:bazel-bin/packages/core/test-helpers/core-test-helpers-http-setup-browser/npm_module_types", "@types/kbn__core-theme-browser": "link:bazel-bin/packages/core/theme/core-theme-browser/npm_module_types", diff --git a/packages/BUILD.bazel b/packages/BUILD.bazel index d4bf2ee0807e5..e6c2b998af76b 100644 --- a/packages/BUILD.bazel +++ b/packages/BUILD.bazel @@ -83,6 +83,7 @@ filegroup( "//packages/core/preboot/core-preboot-server-internal:build", "//packages/core/preboot/core-preboot-server-mocks:build", "//packages/core/preboot/core-preboot-server:build", + "//packages/core/saved-objects/core-saved-objects-common:build", "//packages/core/test-helpers/core-test-helpers-http-setup-browser:build", "//packages/core/theme/core-theme-browser-internal:build", "//packages/core/theme/core-theme-browser-mocks:build", @@ -299,6 +300,7 @@ filegroup( "//packages/core/preboot/core-preboot-server-internal:build_types", "//packages/core/preboot/core-preboot-server-mocks:build_types", "//packages/core/preboot/core-preboot-server:build_types", + "//packages/core/saved-objects/core-saved-objects-common:build_types", "//packages/core/test-helpers/core-test-helpers-http-setup-browser:build_types", "//packages/core/theme/core-theme-browser-internal:build_types", "//packages/core/theme/core-theme-browser-mocks:build_types", diff --git a/packages/core/saved-objects/core-saved-objects-common/BUILD.bazel b/packages/core/saved-objects/core-saved-objects-common/BUILD.bazel new file mode 100644 index 0000000000000..4d321f1c92412 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-common/BUILD.bazel @@ -0,0 +1,126 @@ +load("@npm//@bazel/typescript:index.bzl", "ts_config") +load("@build_bazel_rules_nodejs//:index.bzl", "js_library") +load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project") + +PKG_DIRNAME = "core-saved-objects-common" +PKG_REQUIRE_NAME = "@kbn/core-saved-objects-common" + +SOURCE_FILES = glob( + [ + "src/**/*.ts", + "src/**/*.tsx", + ], + exclude = [ + "**/*.test.*", + "**/*.stories.*", + ], +) + +SRCS = SOURCE_FILES + +filegroup( + name = "srcs", + srcs = SRCS, +) + +NPM_MODULE_EXTRA_FILES = [ + "package.json", +] + +# In this array place runtime dependencies, including other packages and NPM packages +# which must be available for this code to run. +# +# To reference other packages use: +# "//repo/relative/path/to/package" +# eg. "//packages/kbn-utils" +# +# To reference a NPM package use: +# "@npm//name-of-package" +# eg. "@npm//lodash" +RUNTIME_DEPS = [ + "@npm//react" +] + +# In this array place dependencies necessary to build the types, which will include the +# :npm_module_types target of other packages and packages from NPM, including @types/* +# packages. +# +# To reference the types for another package use: +# "//repo/relative/path/to/package:npm_module_types" +# eg. "//packages/kbn-utils:npm_module_types" +# +# References to NPM packages work the same as RUNTIME_DEPS +TYPES_DEPS = [ + "@npm//@types/node", + "@npm//@types/jest", + "@npm//@types/react" +] + +jsts_transpiler( + name = "target_node", + srcs = SRCS, + build_pkg_name = package_name(), +) + +jsts_transpiler( + name = "target_web", + srcs = SRCS, + build_pkg_name = package_name(), + web = True, +) + +ts_config( + name = "tsconfig", + src = "tsconfig.json", + deps = [ + "//:tsconfig.base.json", + "//:tsconfig.bazel.json", + ], +) + +ts_project( + name = "tsc_types", + args = ['--pretty'], + srcs = SRCS, + deps = TYPES_DEPS, + declaration = True, + declaration_map = True, + emit_declaration_only = True, + out_dir = "target_types", + root_dir = "src", + tsconfig = ":tsconfig", +) + +js_library( + name = PKG_DIRNAME, + srcs = NPM_MODULE_EXTRA_FILES, + deps = RUNTIME_DEPS + [":target_node", ":target_web"], + package_name = PKG_REQUIRE_NAME, + visibility = ["//visibility:public"], +) + +pkg_npm( + name = "npm_module", + deps = [":" + PKG_DIRNAME], +) + +filegroup( + name = "build", + srcs = [":npm_module"], + visibility = ["//visibility:public"], +) + +pkg_npm_types( + name = "npm_module_types", + srcs = SRCS, + deps = [":tsc_types"], + package_name = PKG_REQUIRE_NAME, + tsconfig = ":tsconfig", + visibility = ["//visibility:public"], +) + +filegroup( + name = "build_types", + srcs = [":npm_module_types"], + visibility = ["//visibility:public"], +) diff --git a/packages/core/saved-objects/core-saved-objects-common/README.md b/packages/core/saved-objects/core-saved-objects-common/README.md new file mode 100644 index 0000000000000..3619e2b4cf8bb --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-common/README.md @@ -0,0 +1,3 @@ +# @kbn/core-saved-objects-common + +Empty package generated by @kbn/generate diff --git a/packages/core/saved-objects/core-saved-objects-common/jest.config.js b/packages/core/saved-objects/core-saved-objects-common/jest.config.js new file mode 100644 index 0000000000000..9770705e1c49a --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-common/jest.config.js @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../..', + roots: ['/packages/core/saved-objects/core-saved-objects-common'], +}; diff --git a/packages/core/saved-objects/core-saved-objects-common/package.json b/packages/core/saved-objects/core-saved-objects-common/package.json new file mode 100644 index 0000000000000..b138bcd269def --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-common/package.json @@ -0,0 +1,8 @@ +{ + "name": "@kbn/core-saved-objects-common", + "private": true, + "version": "1.0.0", + "main": "./target_node/index.js", + "browser": "./target_web/index.js", + "license": "SSPL-1.0 OR Elastic License 2.0" +} diff --git a/packages/core/saved-objects/core-saved-objects-common/src/index.ts b/packages/core/saved-objects/core-saved-objects-common/src/index.ts new file mode 100644 index 0000000000000..b6e7485e36ab2 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-common/src/index.ts @@ -0,0 +1,11 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export function foo() { + return 'hello world'; +} diff --git a/packages/core/saved-objects/core-saved-objects-common/tsconfig.json b/packages/core/saved-objects/core-saved-objects-common/tsconfig.json new file mode 100644 index 0000000000000..d10eb479b3697 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-common/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../tsconfig.bazel.json", + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "emitDeclarationOnly": true, + "outDir": "target_types", + "rootDir": "src", + "stripInternal": false, + "types": [ + "jest", + "node", + "react" + ] + }, + "include": [ + "src/**/*" + ] +} diff --git a/yarn.lock b/yarn.lock index 03d0d3695ab27..2795a579c28cb 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3351,6 +3351,10 @@ version "0.0.0" uid "" +"@kbn/core-saved-objects-common@link:bazel-bin/packages/core/saved-objects/core-saved-objects-common": + version "0.0.0" + uid "" + "@kbn/core-test-helpers-http-setup-browser@link:bazel-bin/packages/core/test-helpers/core-test-helpers-http-setup-browser": version "0.0.0" uid "" @@ -7110,6 +7114,10 @@ version "0.0.0" uid "" +"@types/kbn__core-saved-objects-common@link:bazel-bin/packages/core/saved-objects/core-saved-objects-common/npm_module_types": + version "0.0.0" + uid "" + "@types/kbn__core-server-internal-base@link:bazel-bin/packages/core/server/internal-base/npm_module_types": version "0.0.0" uid "" From 8f5f18ae04418d0df6f0e26d09daa296c17add9a Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 20 Jul 2022 14:56:27 +0200 Subject: [PATCH 02/46] start moving types around --- .../core-saved-objects-common/src/index.ts | 28 ++- .../src}/saved_objects.ts | 14 ++ .../src/saved_objects_imports.ts | 181 ++++++++++++++++++ .../saved_objects/saved_objects_client.ts | 5 +- src/core/server/saved_objects/import/types.ts | 180 +---------------- src/core/server/saved_objects/types.ts | 42 +--- src/core/server/types.ts | 6 +- 7 files changed, 233 insertions(+), 223 deletions(-) rename {src/core/types => packages/core/saved-objects/core-saved-objects-common/src}/saved_objects.ts (76%) create mode 100644 packages/core/saved-objects/core-saved-objects-common/src/saved_objects_imports.ts diff --git a/packages/core/saved-objects/core-saved-objects-common/src/index.ts b/packages/core/saved-objects/core-saved-objects-common/src/index.ts index b6e7485e36ab2..0210b5482e8e0 100644 --- a/packages/core/saved-objects/core-saved-objects-common/src/index.ts +++ b/packages/core/saved-objects/core-saved-objects-common/src/index.ts @@ -6,6 +6,28 @@ * Side Public License, v 1. */ -export function foo() { - return 'hello world'; -} +export type { + SavedObject, + SavedObjectsNamespaceType, + SavedObjectAttributeSingle, + SavedObjectAttribute, + SavedObjectAttributes, + SavedObjectError, + SavedObjectReference, + SavedObjectsMigrationVersion, +} from './saved_objects'; + +export type { + SavedObjectsImportResponse, + SavedObjectsImportSuccess, + SavedObjectsImportFailure, + SavedObjectsImportRetry, + SavedObjectsImportWarning, + SavedObjectsImportSimpleWarning, + SavedObjectsImportAmbiguousConflictError, + SavedObjectsImportUnsupportedTypeError, + SavedObjectsImportMissingReferencesError, + SavedObjectsImportUnknownError, + SavedObjectsImportActionRequiredWarning, + SavedObjectsImportConflictError, +} from './saved_objects_imports'; diff --git a/src/core/types/saved_objects.ts b/packages/core/saved-objects/core-saved-objects-common/src/saved_objects.ts similarity index 76% rename from src/core/types/saved_objects.ts rename to packages/core/saved-objects/core-saved-objects-common/src/saved_objects.ts index 3a97c2fd6f010..2b8f6d66e67ac 100644 --- a/src/core/types/saved_objects.ts +++ b/packages/core/saved-objects/core-saved-objects-common/src/saved_objects.ts @@ -98,6 +98,20 @@ export interface SavedObject { originId?: string; } +/** + * The namespace type dictates how a saved object can be interacted in relation to namespaces. Each type is mutually exclusive: + * * single (default): This type of saved object is namespace-isolated, e.g., it exists in only one namespace. + * * multiple: This type of saved object is shareable, e.g., it can exist in one or more namespaces. + * * multiple-isolated: This type of saved object is namespace-isolated, e.g., it exists in only one namespace, but object IDs must be + * unique across all namespaces. This is intended to be an intermediate step when objects with a "single" namespace type are being + * converted to a "multiple" namespace type. In other words, objects with a "multiple-isolated" namespace type will be *share-capable*, + * but will not actually be shareable until the namespace type is changed to "multiple". + * * agnostic: This type of saved object is global. + * + * @public + */ +export type SavedObjectsNamespaceType = 'single' | 'multiple' | 'multiple-isolated' | 'agnostic'; + export interface SavedObjectError { error: string; message: string; diff --git a/packages/core/saved-objects/core-saved-objects-common/src/saved_objects_imports.ts b/packages/core/saved-objects/core-saved-objects-common/src/saved_objects_imports.ts new file mode 100644 index 0000000000000..7d6700ed3b47c --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-common/src/saved_objects_imports.ts @@ -0,0 +1,181 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +/** + * Describes a retry operation for importing a saved object. + * @public + */ +export interface SavedObjectsImportRetry { + type: string; + id: string; + overwrite: boolean; + /** + * The object ID that will be created or overwritten. If not specified, the `id` field will be used. + */ + destinationId?: string; + replaceReferences: Array<{ + type: string; + from: string; + to: string; + }>; + /** + * If `createNewCopy` is specified, the new object has a new (undefined) origin ID. This is only needed for the case where + * `createNewCopies` mode is disabled and ambiguous source conflicts are detected. + */ + createNewCopy?: boolean; + /** + * If `ignoreMissingReferences` is specified, reference validation will be skipped for this object. + */ + ignoreMissingReferences?: boolean; +} + +/** + * Represents a failure to import due to a conflict. + * @public + */ +export interface SavedObjectsImportConflictError { + type: 'conflict'; + destinationId?: string; +} + +/** + * Represents a failure to import due to a conflict, which can be resolved in different ways with an overwrite. + * @public + */ +export interface SavedObjectsImportAmbiguousConflictError { + type: 'ambiguous_conflict'; + destinations: Array<{ id: string; title?: string; updatedAt?: string }>; +} + +/** + * Represents a failure to import due to having an unsupported saved object type. + * @public + */ +export interface SavedObjectsImportUnsupportedTypeError { + type: 'unsupported_type'; +} + +/** + * Represents a failure to import due to an unknown reason. + * @public + */ +export interface SavedObjectsImportUnknownError { + type: 'unknown'; + message: string; + statusCode: number; +} + +/** + * Represents a failure to import due to missing references. + * @public + */ +export interface SavedObjectsImportMissingReferencesError { + type: 'missing_references'; + references: Array<{ type: string; id: string }>; +} + +/** + * Represents a failure to import. + * @public + */ +export interface SavedObjectsImportFailure { + id: string; + type: string; + meta: { title?: string; icon?: string }; + /** + * If `overwrite` is specified, an attempt was made to overwrite an existing object. + */ + overwrite?: boolean; + error: + | SavedObjectsImportConflictError + | SavedObjectsImportAmbiguousConflictError + | SavedObjectsImportUnsupportedTypeError + | SavedObjectsImportMissingReferencesError + | SavedObjectsImportUnknownError; +} + +/** + * Represents a successful import. + * @public + */ +export interface SavedObjectsImportSuccess { + id: string; + type: string; + /** + * If `destinationId` is specified, the new object has a new ID that is different from the import ID. + */ + destinationId?: string; + /** + * @deprecated Can be removed when https://github.com/elastic/kibana/issues/91615 is done. + * If `createNewCopy` is specified, the new object has a new (undefined) origin ID. This is only needed for the case where + * `createNewCopies` mode is disabled and ambiguous source conflicts are detected. When `createNewCopies` mode is permanently enabled, + * this field will be redundant and can be removed. + */ + createNewCopy?: boolean; + meta: { + title?: string; + icon?: string; + }; + /** + * If `overwrite` is specified, this object overwrote an existing one (or will do so, in the case of a pending resolution). + */ + overwrite?: boolean; +} + +/** + * A simple informative warning that will be displayed to the user. + * + * @public + */ +export interface SavedObjectsImportSimpleWarning { + type: 'simple'; + /** The translated message to display to the user */ + message: string; +} + +/** + * A warning meant to notify that a specific user action is required to finalize the import + * of some type of object. + * + * @remark The `actionUrl` must be a path relative to the basePath, and not include it. + * + * @public + */ +export interface SavedObjectsImportActionRequiredWarning { + type: 'action_required'; + /** The translated message to display to the user. */ + message: string; + /** The path (without the basePath) that the user should be redirect to address this warning. */ + actionPath: string; + /** An optional label to use for the link button. If unspecified, a default label will be used. */ + buttonLabel?: string; +} + +/** + * Composite type of all the possible types of import warnings. + * + * See {@link SavedObjectsImportSimpleWarning} and {@link SavedObjectsImportActionRequiredWarning} + * for more details. + * + * @public + */ +export type SavedObjectsImportWarning = + | SavedObjectsImportSimpleWarning + | SavedObjectsImportActionRequiredWarning; + +/** + * The response describing the result of an import. + * @public + */ +export interface SavedObjectsImportResponse { + success: boolean; + successCount: number; + successResults?: SavedObjectsImportSuccess[]; + warnings: SavedObjectsImportWarning[]; + errors?: SavedObjectsImportFailure[]; +} diff --git a/src/core/public/saved_objects/saved_objects_client.ts b/src/core/public/saved_objects/saved_objects_client.ts index 69e51557baa07..8a8e3d547ca8a 100644 --- a/src/core/public/saved_objects/saved_objects_client.ts +++ b/src/core/public/saved_objects/saved_objects_client.ts @@ -8,14 +8,15 @@ import { pick, throttle, cloneDeep } from 'lodash'; import type { HttpSetup, HttpFetchOptions } from '@kbn/core-http-browser'; - import type { SavedObject, SavedObjectReference, + SavedObjectsMigrationVersion, +} from '@kbn/core-saved-objects-common'; +import type { SavedObjectsBulkResolveResponse as SavedObjectsBulkResolveResponseServer, SavedObjectsClientContract as SavedObjectsApi, SavedObjectsFindOptions as SavedObjectFindOptionsServer, - SavedObjectsMigrationVersion, SavedObjectsResolveResponse, } from '../../server'; diff --git a/src/core/server/saved_objects/import/types.ts b/src/core/server/saved_objects/import/types.ts index d3a38b48e92cb..fdfbc70e27911 100644 --- a/src/core/server/saved_objects/import/types.ts +++ b/src/core/server/saved_objects/import/types.ts @@ -7,140 +7,11 @@ */ import { Readable } from 'stream'; -import { SavedObject } from '../types'; - -/** - * Describes a retry operation for importing a saved object. - * @public - */ -export interface SavedObjectsImportRetry { - type: string; - id: string; - overwrite: boolean; - /** - * The object ID that will be created or overwritten. If not specified, the `id` field will be used. - */ - destinationId?: string; - replaceReferences: Array<{ - type: string; - from: string; - to: string; - }>; - /** - * If `createNewCopy` is specified, the new object has a new (undefined) origin ID. This is only needed for the case where - * `createNewCopies` mode is disabled and ambiguous source conflicts are detected. - */ - createNewCopy?: boolean; - /** - * If `ignoreMissingReferences` is specified, reference validation will be skipped for this object. - */ - ignoreMissingReferences?: boolean; -} - -/** - * Represents a failure to import due to a conflict. - * @public - */ -export interface SavedObjectsImportConflictError { - type: 'conflict'; - destinationId?: string; -} - -/** - * Represents a failure to import due to a conflict, which can be resolved in different ways with an overwrite. - * @public - */ -export interface SavedObjectsImportAmbiguousConflictError { - type: 'ambiguous_conflict'; - destinations: Array<{ id: string; title?: string; updatedAt?: string }>; -} - -/** - * Represents a failure to import due to having an unsupported saved object type. - * @public - */ -export interface SavedObjectsImportUnsupportedTypeError { - type: 'unsupported_type'; -} - -/** - * Represents a failure to import due to an unknown reason. - * @public - */ -export interface SavedObjectsImportUnknownError { - type: 'unknown'; - message: string; - statusCode: number; -} - -/** - * Represents a failure to import due to missing references. - * @public - */ -export interface SavedObjectsImportMissingReferencesError { - type: 'missing_references'; - references: Array<{ type: string; id: string }>; -} - -/** - * Represents a failure to import. - * @public - */ -export interface SavedObjectsImportFailure { - id: string; - type: string; - meta: { title?: string; icon?: string }; - /** - * If `overwrite` is specified, an attempt was made to overwrite an existing object. - */ - overwrite?: boolean; - error: - | SavedObjectsImportConflictError - | SavedObjectsImportAmbiguousConflictError - | SavedObjectsImportUnsupportedTypeError - | SavedObjectsImportMissingReferencesError - | SavedObjectsImportUnknownError; -} - -/** - * Represents a successful import. - * @public - */ -export interface SavedObjectsImportSuccess { - id: string; - type: string; - /** - * If `destinationId` is specified, the new object has a new ID that is different from the import ID. - */ - destinationId?: string; - /** - * @deprecated Can be removed when https://github.com/elastic/kibana/issues/91615 is done. - * If `createNewCopy` is specified, the new object has a new (undefined) origin ID. This is only needed for the case where - * `createNewCopies` mode is disabled and ambiguous source conflicts are detected. When `createNewCopies` mode is permanently enabled, - * this field will be redundant and can be removed. - */ - createNewCopy?: boolean; - meta: { - title?: string; - icon?: string; - }; - /** - * If `overwrite` is specified, this object overwrote an existing one (or will do so, in the case of a pending resolution). - */ - overwrite?: boolean; -} - -/** - * The response describing the result of an import. - * @public - */ -export interface SavedObjectsImportResponse { - success: boolean; - successCount: number; - successResults?: SavedObjectsImportSuccess[]; - warnings: SavedObjectsImportWarning[]; - errors?: SavedObjectsImportFailure[]; -} +import { + SavedObject, + SavedObjectsImportRetry, + SavedObjectsImportWarning, +} from '@kbn/core-saved-objects-common'; /** * Options to control the import operation. @@ -176,47 +47,6 @@ export interface SavedObjectsResolveImportErrorsOptions { export type CreatedObject = SavedObject & { destinationId?: string }; -/** - * A simple informative warning that will be displayed to the user. - * - * @public - */ -export interface SavedObjectsImportSimpleWarning { - type: 'simple'; - /** The translated message to display to the user */ - message: string; -} - -/** - * A warning meant to notify that a specific user action is required to finalize the import - * of some type of object. - * - * @remark The `actionUrl` must be a path relative to the basePath, and not include it. - * - * @public - */ -export interface SavedObjectsImportActionRequiredWarning { - type: 'action_required'; - /** The translated message to display to the user. */ - message: string; - /** The path (without the basePath) that the user should be redirect to address this warning. */ - actionPath: string; - /** An optional label to use for the link button. If unspecified, a default label will be used. */ - buttonLabel?: string; -} - -/** - * Composite type of all the possible types of import warnings. - * - * See {@link SavedObjectsImportSimpleWarning} and {@link SavedObjectsImportActionRequiredWarning} - * for more details. - * - * @public - */ -export type SavedObjectsImportWarning = - | SavedObjectsImportSimpleWarning - | SavedObjectsImportActionRequiredWarning; - /** * Result from a {@link SavedObjectsImportHook | import hook} * diff --git a/src/core/server/saved_objects/types.ts b/src/core/server/saved_objects/types.ts index 134289cb2b493..a67c0808328cb 100644 --- a/src/core/server/saved_objects/types.ts +++ b/src/core/server/saved_objects/types.ts @@ -8,6 +8,7 @@ import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; +import type { SavedObject, SavedObjectsNamespaceType } from '@kbn/core-saved-objects-common'; import { SavedObjectsClient } from './service/saved_objects_client'; import { SavedObjectsTypeMappingDefinition } from './mappings'; import { SavedObjectMigrationMap } from './migrations'; @@ -15,35 +16,8 @@ import { SavedObjectsExportTransform } from './export'; import { SavedObjectsImportHook } from './import/types'; import { SavedObjectsValidationMap } from './validation'; -export type { - SavedObjectsImportResponse, - SavedObjectsImportSuccess, - SavedObjectsImportConflictError, - SavedObjectsImportAmbiguousConflictError, - SavedObjectsImportUnsupportedTypeError, - SavedObjectsImportMissingReferencesError, - SavedObjectsImportUnknownError, - SavedObjectsImportFailure, - SavedObjectsImportRetry, - SavedObjectsImportActionRequiredWarning, - SavedObjectsImportSimpleWarning, - SavedObjectsImportWarning, -} from './import/types'; - -import { SavedObject } from '../../types'; - type KueryNode = any; -export type { - SavedObjectAttributes, - SavedObjectAttribute, - SavedObjectAttributeSingle, - SavedObject, - SavedObjectError, - SavedObjectReference, - SavedObjectsMigrationVersion, -} from '../../types'; - /** * Meta information about the SavedObjectService's status. Available to plugins via {@link CoreSetup.status}. * @@ -236,20 +210,6 @@ export type MutatingOperationRefreshSetting = boolean | 'wait_for'; */ export type SavedObjectsClientContract = Pick; -/** - * The namespace type dictates how a saved object can be interacted in relation to namespaces. Each type is mutually exclusive: - * * single (default): This type of saved object is namespace-isolated, e.g., it exists in only one namespace. - * * multiple: This type of saved object is shareable, e.g., it can exist in one or more namespaces. - * * multiple-isolated: This type of saved object is namespace-isolated, e.g., it exists in only one namespace, but object IDs must be - * unique across all namespaces. This is intended to be an intermediate step when objects with a "single" namespace type are being - * converted to a "multiple" namespace type. In other words, objects with a "multiple-isolated" namespace type will be *share-capable*, - * but will not actually be shareable until the namespace type is changed to "multiple". - * * agnostic: This type of saved object is global. - * - * @public - */ -export type SavedObjectsNamespaceType = 'single' | 'multiple' | 'multiple-isolated' | 'agnostic'; - /** * @public */ diff --git a/src/core/server/types.ts b/src/core/server/types.ts index 1bcdd1ac09535..2523321d20068 100644 --- a/src/core/server/types.ts +++ b/src/core/server/types.ts @@ -8,7 +8,7 @@ /** This module is intended for consumption by public to avoid import issues with server-side code */ export type { EnvironmentMode, PackageInfo } from '@kbn/config'; -export type { PluginOpaqueId } from './plugins/types'; +export type { PluginOpaqueId } from '@kbn/core-base-common'; export type { SavedObjectsImportResponse, SavedObjectsImportSuccess, @@ -26,9 +26,12 @@ export type { SavedObjectAttribute, SavedObjectAttributeSingle, SavedObject, + SavedObjectsNamespaceType, SavedObjectError, SavedObjectReference, SavedObjectsMigrationVersion, +} from '@kbn/core-saved-objects-common'; +export type { SavedObjectStatusMeta, SavedObjectsFindOptionsReference, SavedObjectsFindOptions, @@ -36,7 +39,6 @@ export type { SavedObjectsBaseOptions, MutatingOperationRefreshSetting, SavedObjectsClientContract, - SavedObjectsNamespaceType, } from './saved_objects/types'; export type { SavedObjectReferenceWithContext, From ef4da90fe108570d48d100ffffc16f80ef2bfbac Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 20 Jul 2022 15:49:31 +0200 Subject: [PATCH 03/46] start fixing imports --- .../service/lib/repository_with_proxy.test.ts | 2 +- .../export/apply_export_transforms.test.ts | 2 +- .../saved_objects/export/apply_export_transforms.ts | 2 +- .../export/collect_exported_objects.test.ts | 2 +- .../export/collect_exported_objects.ts | 2 +- src/core/server/saved_objects/export/errors.ts | 2 +- .../export/saved_objects_exporter.test.ts | 2 +- .../saved_objects/export/saved_objects_exporter.ts | 3 ++- .../server/saved_objects/export/sort_objects.ts | 2 +- src/core/server/saved_objects/export/types.ts | 3 ++- src/core/server/saved_objects/export/utils.test.ts | 2 +- src/core/server/saved_objects/export/utils.ts | 2 +- src/core/server/saved_objects/import/errors.ts | 2 +- .../import/import_saved_objects.test.ts | 10 +++++----- .../saved_objects/import/import_saved_objects.ts | 10 +++++----- src/core/server/saved_objects/import/index.ts | 12 ------------ .../import/lib/check_conflicts.test.ts | 8 ++++++-- .../saved_objects/import/lib/check_conflicts.ts | 6 +++--- .../import/lib/check_origin_conflicts.test.ts | 6 +++--- .../import/lib/check_origin_conflicts.ts | 7 +++++-- .../import/lib/collect_saved_objects.ts | 3 +-- .../import/lib/create_objects_filter.ts | 3 +-- .../import/lib/create_saved_objects.test.ts | 3 ++- .../import/lib/create_saved_objects.ts | 4 +++- .../import/lib/execute_import_hooks.test.ts | 4 ++-- .../import/lib/execute_import_hooks.ts | 4 ++-- .../saved_objects/import/lib/extract_errors.test.ts | 2 +- .../saved_objects/import/lib/extract_errors.ts | 4 ++-- .../lib/get_import_state_map_for_retries.test.ts | 3 +-- .../import/lib/get_import_state_map_for_retries.ts | 2 +- .../saved_objects/import/lib/regenerate_ids.test.ts | 2 +- .../saved_objects/import/lib/regenerate_ids.ts | 2 +- .../saved_objects/import/lib/split_overwrites.ts | 3 +-- .../saved_objects/import/lib/validate_references.ts | 9 +++++++-- .../import/lib/validate_retries.test.ts | 2 +- .../saved_objects/import/lib/validate_retries.ts | 2 +- .../import/resolve_import_errors.test.ts | 7 +++---- .../saved_objects/import/resolve_import_errors.ts | 12 +++++++----- .../saved_objects/import/saved_objects_importer.ts | 2 +- src/core/server/saved_objects/index.ts | 13 ------------- .../migrations/core/document_migrator.ts | 8 ++++---- .../saved_objects/migrations/initial_state.ts | 2 +- .../migrations/run_resilient_migrator.ts | 2 +- .../server/saved_objects/saved_objects_service.ts | 8 ++------ .../server/saved_objects/serialization/types.ts | 2 +- .../lib/collect_multi_namespace_references.ts | 3 ++- .../service/lib/internal_bulk_resolve.test.ts | 3 ++- .../service/lib/internal_bulk_resolve.ts | 3 ++- .../saved_objects/service/lib/internal_utils.ts | 2 +- .../saved_objects/service/lib/repository.test.ts | 9 ++------- .../server/saved_objects/service/lib/repository.ts | 3 +-- .../service/lib/update_objects_spaces.ts | 7 ++----- .../saved_objects/service/saved_objects_client.ts | 10 ++++++---- src/core/types/index.ts | 11 ++++++++++- 54 files changed, 118 insertions(+), 128 deletions(-) diff --git a/src/core/server/integration_tests/saved_objects/service/lib/repository_with_proxy.test.ts b/src/core/server/integration_tests/saved_objects/service/lib/repository_with_proxy.test.ts index b82cb54053482..3a27af1383244 100644 --- a/src/core/server/integration_tests/saved_objects/service/lib/repository_with_proxy.test.ts +++ b/src/core/server/integration_tests/saved_objects/service/lib/repository_with_proxy.test.ts @@ -9,8 +9,8 @@ import Hapi from '@hapi/hapi'; import h2o2 from '@hapi/h2o2'; import { URL } from 'url'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; import { ISavedObjectsRepository } from '../../../../saved_objects/service/lib/repository'; -import { SavedObject } from '../../../../saved_objects/types'; import { InternalCoreSetup, InternalCoreStart } from '../../../../internal_types'; import { Root } from '../../../../root'; import * as kbnTestServer from '../../../../../test_helpers/kbn_server'; diff --git a/src/core/server/saved_objects/export/apply_export_transforms.test.ts b/src/core/server/saved_objects/export/apply_export_transforms.test.ts index 561c1ee1aed8b..c3f091b170ab7 100644 --- a/src/core/server/saved_objects/export/apply_export_transforms.test.ts +++ b/src/core/server/saved_objects/export/apply_export_transforms.test.ts @@ -8,7 +8,7 @@ import { CoreKibanaRequest } from '@kbn/core-http-router-server-internal'; import { httpServerMock } from '@kbn/core-http-server-mocks'; -import { SavedObject } from '../../../types'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; import { applyExportTransforms } from './apply_export_transforms'; import { SavedObjectsExportTransform } from './types'; diff --git a/src/core/server/saved_objects/export/apply_export_transforms.ts b/src/core/server/saved_objects/export/apply_export_transforms.ts index c105ccd7a7ad5..1742b4ff1a2a3 100644 --- a/src/core/server/saved_objects/export/apply_export_transforms.ts +++ b/src/core/server/saved_objects/export/apply_export_transforms.ts @@ -7,7 +7,7 @@ */ import type { KibanaRequest } from '@kbn/core-http-server'; -import { SavedObject } from '../../../types'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; import { SavedObjectsExportError } from './errors'; import { SavedObjectsExportTransform, SavedObjectsExportTransformContext } from './types'; import { getObjKey, SavedObjectComparator } from './utils'; diff --git a/src/core/server/saved_objects/export/collect_exported_objects.test.ts b/src/core/server/saved_objects/export/collect_exported_objects.test.ts index 7a483d3a9af20..84520efa10a53 100644 --- a/src/core/server/saved_objects/export/collect_exported_objects.test.ts +++ b/src/core/server/saved_objects/export/collect_exported_objects.test.ts @@ -7,10 +7,10 @@ */ import { httpServerMock } from '@kbn/core-http-server-mocks'; +import type { SavedObject, SavedObjectError } from '@kbn/core-saved-objects-common'; import { applyExportTransformsMock } from './collect_exported_objects.test.mocks'; import { savedObjectsClientMock } from '../../mocks'; import { loggerMock } from '@kbn/logging-mocks'; -import { SavedObject, SavedObjectError } from '../../../types'; import { SavedObjectTypeRegistry } from '../saved_objects_type_registry'; import type { SavedObjectsExportTransform } from './types'; import { collectExportedObjects, ExclusionReason } from './collect_exported_objects'; diff --git a/src/core/server/saved_objects/export/collect_exported_objects.ts b/src/core/server/saved_objects/export/collect_exported_objects.ts index 57a83fc399291..4aea6de98fc2d 100644 --- a/src/core/server/saved_objects/export/collect_exported_objects.ts +++ b/src/core/server/saved_objects/export/collect_exported_objects.ts @@ -8,7 +8,7 @@ import type { Logger } from '@kbn/logging'; import type { KibanaRequest } from '@kbn/core-http-server'; -import type { SavedObject } from '../../../types'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; import { SavedObjectsClientContract, SavedObjectsExportablePredicate } from '../types'; import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry'; import type { SavedObjectsExportTransform } from './types'; diff --git a/src/core/server/saved_objects/export/errors.ts b/src/core/server/saved_objects/export/errors.ts index 0110e68142fa0..6ca23c358f931 100644 --- a/src/core/server/saved_objects/export/errors.ts +++ b/src/core/server/saved_objects/export/errors.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedObject } from '../../../types'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; /** * @public diff --git a/src/core/server/saved_objects/export/saved_objects_exporter.test.ts b/src/core/server/saved_objects/export/saved_objects_exporter.test.ts index 6b0e0e3b277d9..8b4604087141c 100644 --- a/src/core/server/saved_objects/export/saved_objects_exporter.test.ts +++ b/src/core/server/saved_objects/export/saved_objects_exporter.test.ts @@ -7,7 +7,7 @@ */ import { httpServerMock } from '@kbn/core-http-server-mocks'; -import type { SavedObject } from '../../../types'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; import { SavedObjectsExporter } from './saved_objects_exporter'; import { savedObjectsClientMock } from '../service/saved_objects_client.mock'; import { SavedObjectTypeRegistry } from '../saved_objects_type_registry'; diff --git a/src/core/server/saved_objects/export/saved_objects_exporter.ts b/src/core/server/saved_objects/export/saved_objects_exporter.ts index ae9660256c3a5..19ff024b6f354 100644 --- a/src/core/server/saved_objects/export/saved_objects_exporter.ts +++ b/src/core/server/saved_objects/export/saved_objects_exporter.ts @@ -9,7 +9,8 @@ import type { Readable } from 'stream'; import { createListStream } from '@kbn/utils'; import type { Logger } from '@kbn/logging'; -import { SavedObject, SavedObjectsClientContract } from '../types'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; +import type { SavedObjectsClientContract } from '../types'; import { SavedObjectsFindResult } from '../service'; import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry'; import { sortObjects } from './sort_objects'; diff --git a/src/core/server/saved_objects/export/sort_objects.ts b/src/core/server/saved_objects/export/sort_objects.ts index 3b73f889933b9..487622877e25c 100644 --- a/src/core/server/saved_objects/export/sort_objects.ts +++ b/src/core/server/saved_objects/export/sort_objects.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedObject } from '../types'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; export function sortObjects(savedObjects: SavedObject[]): SavedObject[] { const path = new Set(); diff --git a/src/core/server/saved_objects/export/types.ts b/src/core/server/saved_objects/export/types.ts index f766a4ce7f6a1..661f9a861c441 100644 --- a/src/core/server/saved_objects/export/types.ts +++ b/src/core/server/saved_objects/export/types.ts @@ -7,7 +7,8 @@ */ import type { KibanaRequest } from '@kbn/core-http-server'; -import { SavedObject, SavedObjectsFindOptionsReference } from '../types'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; +import { SavedObjectsFindOptionsReference } from '../types'; /** @public */ export interface SavedObjectExportBaseOptions { diff --git a/src/core/server/saved_objects/export/utils.test.ts b/src/core/server/saved_objects/export/utils.test.ts index b34aadb682629..6088217bd9201 100644 --- a/src/core/server/saved_objects/export/utils.test.ts +++ b/src/core/server/saved_objects/export/utils.test.ts @@ -6,8 +6,8 @@ * Side Public License, v 1. */ +import type { SavedObject } from '@kbn/core-saved-objects-common'; import { byIdAscComparator, getPreservedOrderComparator } from './utils'; -import { SavedObject } from '../../../types'; const createObj = (id: string): SavedObject => ({ id, diff --git a/src/core/server/saved_objects/export/utils.ts b/src/core/server/saved_objects/export/utils.ts index 1caa80785753d..dbace21e98ca6 100644 --- a/src/core/server/saved_objects/export/utils.ts +++ b/src/core/server/saved_objects/export/utils.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedObject } from '../../../types'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; export type SavedObjectComparator = (a: SavedObject, b: SavedObject) => number; diff --git a/src/core/server/saved_objects/import/errors.ts b/src/core/server/saved_objects/import/errors.ts index 19754b384c27f..c0350c7eac7f8 100644 --- a/src/core/server/saved_objects/import/errors.ts +++ b/src/core/server/saved_objects/import/errors.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedObject } from '../../../types'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; /** * @public diff --git a/src/core/server/saved_objects/import/import_saved_objects.test.ts b/src/core/server/saved_objects/import/import_saved_objects.test.ts index 046b9d3505cde..98550c8113b6d 100644 --- a/src/core/server/saved_objects/import/import_saved_objects.test.ts +++ b/src/core/server/saved_objects/import/import_saved_objects.test.ts @@ -19,17 +19,17 @@ import { import { Readable } from 'stream'; import { v4 as uuidv4 } from 'uuid'; -import { - SavedObjectsClientContract, - SavedObjectsType, +import type { SavedObject, SavedObjectsImportFailure, -} from '../types'; + SavedObjectsImportWarning, +} from '@kbn/core-saved-objects-common'; +import { SavedObjectsClientContract, SavedObjectsType } from '../types'; import { savedObjectsClientMock } from '../../mocks'; import { ISavedObjectTypeRegistry } from '..'; import { typeRegistryMock } from '../saved_objects_type_registry.mock'; import { importSavedObjectsFromStream, ImportSavedObjectsOptions } from './import_saved_objects'; -import { SavedObjectsImportHook, SavedObjectsImportWarning } from './types'; +import { SavedObjectsImportHook } from './types'; import type { ImportStateMap } from './lib'; describe('#importSavedObjectsFromStream', () => { diff --git a/src/core/server/saved_objects/import/import_saved_objects.ts b/src/core/server/saved_objects/import/import_saved_objects.ts index 9e9f5f8b050dc..ea9f14de6506c 100644 --- a/src/core/server/saved_objects/import/import_saved_objects.ts +++ b/src/core/server/saved_objects/import/import_saved_objects.ts @@ -7,13 +7,13 @@ */ import { Readable } from 'stream'; -import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry'; -import { SavedObjectsClientContract } from '../types'; -import { +import type { SavedObjectsImportFailure, SavedObjectsImportResponse, - SavedObjectsImportHook, -} from './types'; +} from '@kbn/core-saved-objects-common'; +import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry'; +import { SavedObjectsClientContract } from '../types'; +import { SavedObjectsImportHook } from './types'; import { checkReferenceOrigins, validateReferences, diff --git a/src/core/server/saved_objects/import/index.ts b/src/core/server/saved_objects/import/index.ts index 4832038b342d2..c299b92d4c5f9 100644 --- a/src/core/server/saved_objects/import/index.ts +++ b/src/core/server/saved_objects/import/index.ts @@ -9,21 +9,9 @@ export { SavedObjectsImporter } from './saved_objects_importer'; export type { ISavedObjectsImporter } from './saved_objects_importer'; export type { - SavedObjectsImportResponse, - SavedObjectsImportSuccess, - SavedObjectsImportFailure, SavedObjectsImportOptions, - SavedObjectsImportConflictError, - SavedObjectsImportAmbiguousConflictError, - SavedObjectsImportMissingReferencesError, - SavedObjectsImportUnknownError, - SavedObjectsImportUnsupportedTypeError, SavedObjectsResolveImportErrorsOptions, - SavedObjectsImportRetry, SavedObjectsImportHook, SavedObjectsImportHookResult, - SavedObjectsImportSimpleWarning, - SavedObjectsImportActionRequiredWarning, - SavedObjectsImportWarning, } from './types'; export { SavedObjectsImportError } from './errors'; diff --git a/src/core/server/saved_objects/import/lib/check_conflicts.test.ts b/src/core/server/saved_objects/import/lib/check_conflicts.test.ts index a9c534bd7e36b..e78e438cd3a2d 100644 --- a/src/core/server/saved_objects/import/lib/check_conflicts.test.ts +++ b/src/core/server/saved_objects/import/lib/check_conflicts.test.ts @@ -7,8 +7,12 @@ */ import { savedObjectsClientMock } from '../../../mocks'; -import { SavedObjectReference, SavedObjectsImportRetry } from '../../../../public'; -import { SavedObjectsClientContract, SavedObject } from '../../types'; +import type { + SavedObject, + SavedObjectReference, + SavedObjectsImportRetry, +} from '@kbn/core-saved-objects-common'; +import { SavedObjectsClientContract } from '../../types'; import { SavedObjectsErrorHelpers } from '../../service'; import { checkConflicts } from './check_conflicts'; diff --git a/src/core/server/saved_objects/import/lib/check_conflicts.ts b/src/core/server/saved_objects/import/lib/check_conflicts.ts index 3ab4b03e791b0..2323b2785e756 100644 --- a/src/core/server/saved_objects/import/lib/check_conflicts.ts +++ b/src/core/server/saved_objects/import/lib/check_conflicts.ts @@ -7,13 +7,13 @@ */ import { v4 as uuidv4 } from 'uuid'; -import { +import type { SavedObject, - SavedObjectsClientContract, SavedObjectsImportFailure, SavedObjectError, SavedObjectsImportRetry, -} from '../../types'; +} from '@kbn/core-saved-objects-common'; +import { SavedObjectsClientContract } from '../../types'; import type { ImportStateMap } from './types'; interface CheckConflictsParams { diff --git a/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts b/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts index 30f40e5e84c62..9d85f4a563035 100644 --- a/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts +++ b/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts @@ -8,13 +8,13 @@ import { mockCreateOriginQuery } from './check_reference_origins.test.mock'; -import { - SavedObjectsClientContract, +import type { SavedObjectReference, SavedObject, SavedObjectsImportFailure, SavedObjectsImportRetry, -} from '../../types'; +} from '@kbn/core-saved-objects-common'; +import { SavedObjectsClientContract } from '../../types'; import { checkOriginConflicts } from './check_origin_conflicts'; import { savedObjectsClientMock } from '../../../mocks'; import { typeRegistryMock } from '../../saved_objects_type_registry.mock'; diff --git a/src/core/server/saved_objects/import/lib/check_origin_conflicts.ts b/src/core/server/saved_objects/import/lib/check_origin_conflicts.ts index 207eb59b126cd..71dbe6bcbc4d0 100644 --- a/src/core/server/saved_objects/import/lib/check_origin_conflicts.ts +++ b/src/core/server/saved_objects/import/lib/check_origin_conflicts.ts @@ -10,10 +10,10 @@ import pMap from 'p-map'; import { v4 as uuidv4 } from 'uuid'; import type { SavedObject, - SavedObjectsClientContract, SavedObjectsImportFailure, SavedObjectsImportRetry, -} from '../../types'; +} from '@kbn/core-saved-objects-common'; +import type { SavedObjectsClientContract } from '../../types'; import { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import { getObjectKey } from '../../service/lib/internal_utils'; import type { ImportStateMap } from './types'; @@ -44,14 +44,17 @@ interface InexactMatch { object: SavedObject; destinations: Array<{ id: string; title?: string; updatedAt?: string }>; } + interface Left { tag: 'left'; value: InexactMatch; } + interface Right { tag: 'right'; value: SavedObject; } + type Either = Left | Right; const isLeft = (object: Either): object is Left => object.tag === 'left'; diff --git a/src/core/server/saved_objects/import/lib/collect_saved_objects.ts b/src/core/server/saved_objects/import/lib/collect_saved_objects.ts index 66d75d7af5073..e86ff1f70794d 100644 --- a/src/core/server/saved_objects/import/lib/collect_saved_objects.ts +++ b/src/core/server/saved_objects/import/lib/collect_saved_objects.ts @@ -14,8 +14,7 @@ import { createPromiseFromStreams, } from '@kbn/utils'; -import { SavedObject } from '../../types'; -import { SavedObjectsImportFailure } from '../types'; +import type { SavedObject, SavedObjectsImportFailure } from '@kbn/core-saved-objects-common'; import { SavedObjectsImportError } from '../errors'; import { getNonUniqueEntries } from './get_non_unique_entries'; import { createLimitStream } from './create_limit_stream'; diff --git a/src/core/server/saved_objects/import/lib/create_objects_filter.ts b/src/core/server/saved_objects/import/lib/create_objects_filter.ts index 295104846a868..4b830e80fa6cb 100644 --- a/src/core/server/saved_objects/import/lib/create_objects_filter.ts +++ b/src/core/server/saved_objects/import/lib/create_objects_filter.ts @@ -6,8 +6,7 @@ * Side Public License, v 1. */ -import { SavedObject } from '../../types'; -import { SavedObjectsImportRetry } from '../types'; +import type { SavedObject, SavedObjectsImportRetry } from '@kbn/core-saved-objects-common'; export function createObjectsFilter(retries: SavedObjectsImportRetry[]) { const retryKeys = new Set(retries.map((retry) => `${retry.type}:${retry.id}`)); diff --git a/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts b/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts index 7f8b67406773e..88ce8ce3b6886 100644 --- a/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts +++ b/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts @@ -7,8 +7,9 @@ */ import { savedObjectsClientMock } from '../../../mocks'; +import type { SavedObject, SavedObjectsImportFailure } from '@kbn/core-saved-objects-common'; import { createSavedObjects } from './create_saved_objects'; -import { SavedObjectsClientContract, SavedObject, SavedObjectsImportFailure } from '../../types'; +import { SavedObjectsClientContract } from '../../types'; import { SavedObjectsErrorHelpers } from '../../service'; import { extractErrors } from './extract_errors'; diff --git a/src/core/server/saved_objects/import/lib/create_saved_objects.ts b/src/core/server/saved_objects/import/lib/create_saved_objects.ts index f3260e4968d00..6423f793418b3 100644 --- a/src/core/server/saved_objects/import/lib/create_saved_objects.ts +++ b/src/core/server/saved_objects/import/lib/create_saved_objects.ts @@ -6,7 +6,8 @@ * Side Public License, v 1. */ -import { SavedObject, SavedObjectsClientContract, SavedObjectsImportFailure } from '../../types'; +import type { SavedObject, SavedObjectsImportFailure } from '@kbn/core-saved-objects-common'; +import { SavedObjectsClientContract } from '../../types'; import { extractErrors } from './extract_errors'; import { CreatedObject } from '../types'; import type { ImportStateMap } from './types'; @@ -20,6 +21,7 @@ export interface CreateSavedObjectsParams { overwrite?: boolean; refresh?: boolean | 'wait_for'; } + export interface CreateSavedObjectsResult { createdObjects: Array>; errors: SavedObjectsImportFailure[]; diff --git a/src/core/server/saved_objects/import/lib/execute_import_hooks.test.ts b/src/core/server/saved_objects/import/lib/execute_import_hooks.test.ts index cf4bf718e6782..64b2c60c7f16b 100644 --- a/src/core/server/saved_objects/import/lib/execute_import_hooks.test.ts +++ b/src/core/server/saved_objects/import/lib/execute_import_hooks.test.ts @@ -6,8 +6,8 @@ * Side Public License, v 1. */ -import { SavedObject } from '../../types'; -import { SavedObjectsImportHookResult, SavedObjectsImportWarning } from '../types'; +import type { SavedObject, SavedObjectsImportWarning } from '@kbn/core-saved-objects-common'; +import { SavedObjectsImportHookResult } from '../types'; import { executeImportHooks } from './execute_import_hooks'; const createObject = (type: string, id: string): SavedObject => ({ diff --git a/src/core/server/saved_objects/import/lib/execute_import_hooks.ts b/src/core/server/saved_objects/import/lib/execute_import_hooks.ts index c0b5ae0437b2c..a94bf822f7f75 100644 --- a/src/core/server/saved_objects/import/lib/execute_import_hooks.ts +++ b/src/core/server/saved_objects/import/lib/execute_import_hooks.ts @@ -6,8 +6,8 @@ * Side Public License, v 1. */ -import { SavedObject } from '../../types'; -import { SavedObjectsImportHook, SavedObjectsImportWarning } from '../types'; +import type { SavedObject, SavedObjectsImportWarning } from '@kbn/core-saved-objects-common'; +import { SavedObjectsImportHook } from '../types'; export interface ExecuteImportHooksOptions { objects: SavedObject[]; diff --git a/src/core/server/saved_objects/import/lib/extract_errors.test.ts b/src/core/server/saved_objects/import/lib/extract_errors.test.ts index a355094f07117..400db2077d8c7 100644 --- a/src/core/server/saved_objects/import/lib/extract_errors.test.ts +++ b/src/core/server/saved_objects/import/lib/extract_errors.test.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedObject } from '../../types'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; import { extractErrors } from './extract_errors'; import { SavedObjectsErrorHelpers } from '../../service'; import { CreatedObject } from '../types'; diff --git a/src/core/server/saved_objects/import/lib/extract_errors.ts b/src/core/server/saved_objects/import/lib/extract_errors.ts index 12d7612a4f960..15164f9873538 100644 --- a/src/core/server/saved_objects/import/lib/extract_errors.ts +++ b/src/core/server/saved_objects/import/lib/extract_errors.ts @@ -6,8 +6,8 @@ * Side Public License, v 1. */ -import { SavedObject } from '../../types'; -import { SavedObjectsImportFailure, CreatedObject } from '../types'; +import type { SavedObject, SavedObjectsImportFailure } from '@kbn/core-saved-objects-common'; +import { CreatedObject } from '../types'; export function extractErrors( // TODO: define saved object type diff --git a/src/core/server/saved_objects/import/lib/get_import_state_map_for_retries.test.ts b/src/core/server/saved_objects/import/lib/get_import_state_map_for_retries.test.ts index af5aca10ba289..d598326afa136 100644 --- a/src/core/server/saved_objects/import/lib/get_import_state_map_for_retries.test.ts +++ b/src/core/server/saved_objects/import/lib/get_import_state_map_for_retries.test.ts @@ -6,8 +6,7 @@ * Side Public License, v 1. */ -import type { SavedObject } from '../../types'; -import type { SavedObjectsImportRetry } from '../types'; +import type { SavedObject, SavedObjectsImportRetry } from '@kbn/core-saved-objects-common'; import { getImportStateMapForRetries } from './get_import_state_map_for_retries'; describe('#getImportStateMapForRetries', () => { diff --git a/src/core/server/saved_objects/import/lib/get_import_state_map_for_retries.ts b/src/core/server/saved_objects/import/lib/get_import_state_map_for_retries.ts index 3066ae72738a4..43a6730f33550 100644 --- a/src/core/server/saved_objects/import/lib/get_import_state_map_for_retries.ts +++ b/src/core/server/saved_objects/import/lib/get_import_state_map_for_retries.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedObject, SavedObjectsImportRetry } from '../../types'; +import { SavedObject, SavedObjectsImportRetry } from '@kbn/core-saved-objects-common'; import type { ImportStateMap } from './types'; interface GetImportStateMapForRetriesParams { diff --git a/src/core/server/saved_objects/import/lib/regenerate_ids.test.ts b/src/core/server/saved_objects/import/lib/regenerate_ids.test.ts index d22b9431367d4..f8a8c502af38a 100644 --- a/src/core/server/saved_objects/import/lib/regenerate_ids.test.ts +++ b/src/core/server/saved_objects/import/lib/regenerate_ids.test.ts @@ -6,8 +6,8 @@ * Side Public License, v 1. */ +import type { SavedObject } from '@kbn/core-saved-objects-common'; import { regenerateIds } from './regenerate_ids'; -import { SavedObject } from '../../types'; jest.mock('uuid', () => ({ v4: jest diff --git a/src/core/server/saved_objects/import/lib/regenerate_ids.ts b/src/core/server/saved_objects/import/lib/regenerate_ids.ts index 174658555aaf1..1d895c8c7dabf 100644 --- a/src/core/server/saved_objects/import/lib/regenerate_ids.ts +++ b/src/core/server/saved_objects/import/lib/regenerate_ids.ts @@ -7,7 +7,7 @@ */ import { v4 as uuidv4 } from 'uuid'; -import { SavedObject } from '../../types'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; import type { ImportStateMap } from './types'; /** diff --git a/src/core/server/saved_objects/import/lib/split_overwrites.ts b/src/core/server/saved_objects/import/lib/split_overwrites.ts index 8f2d15d37ea09..818b6e512dcc2 100644 --- a/src/core/server/saved_objects/import/lib/split_overwrites.ts +++ b/src/core/server/saved_objects/import/lib/split_overwrites.ts @@ -6,8 +6,7 @@ * Side Public License, v 1. */ -import { SavedObject } from '../../types'; -import { SavedObjectsImportRetry } from '../types'; +import type { SavedObject, SavedObjectsImportRetry } from '@kbn/core-saved-objects-common'; export function splitOverwrites( savedObjects: Array>, diff --git a/src/core/server/saved_objects/import/lib/validate_references.ts b/src/core/server/saved_objects/import/lib/validate_references.ts index b454bf8c887a4..9d9c92ec4a625 100644 --- a/src/core/server/saved_objects/import/lib/validate_references.ts +++ b/src/core/server/saved_objects/import/lib/validate_references.ts @@ -6,8 +6,12 @@ * Side Public License, v 1. */ -import { SavedObject, SavedObjectsClientContract } from '../../types'; -import { SavedObjectsImportFailure, SavedObjectsImportRetry } from '../types'; +import type { + SavedObject, + SavedObjectsImportFailure, + SavedObjectsImportRetry, +} from '@kbn/core-saved-objects-common'; +import { SavedObjectsClientContract } from '../../types'; import { SavedObjectsImportError } from '../errors'; import type { ImportStateMap } from './types'; @@ -16,6 +20,7 @@ const REF_TYPES_TO_VALIDATE = ['index-pattern', 'search']; function filterReferencesToValidate({ type }: { type: string }) { return REF_TYPES_TO_VALIDATE.includes(type); } + const getObjectsToSkip = (retries: SavedObjectsImportRetry[] = []) => retries.reduce( (acc, { type, id, ignoreMissingReferences }) => diff --git a/src/core/server/saved_objects/import/lib/validate_retries.test.ts b/src/core/server/saved_objects/import/lib/validate_retries.test.ts index e81a51b99fe8c..984068b59c575 100644 --- a/src/core/server/saved_objects/import/lib/validate_retries.test.ts +++ b/src/core/server/saved_objects/import/lib/validate_retries.test.ts @@ -6,8 +6,8 @@ * Side Public License, v 1. */ +import type { SavedObjectsImportRetry } from '@kbn/core-saved-objects-common'; import { validateRetries } from './validate_retries'; -import { SavedObjectsImportRetry } from '../types'; import { SavedObjectsImportError } from '../errors'; import { getNonUniqueEntries } from './get_non_unique_entries'; diff --git a/src/core/server/saved_objects/import/lib/validate_retries.ts b/src/core/server/saved_objects/import/lib/validate_retries.ts index f1c06f73c63ae..745bb9fd42354 100644 --- a/src/core/server/saved_objects/import/lib/validate_retries.ts +++ b/src/core/server/saved_objects/import/lib/validate_retries.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedObjectsImportRetry } from '../types'; +import type { SavedObjectsImportRetry } from '@kbn/core-saved-objects-common'; import { getNonUniqueEntries } from './get_non_unique_entries'; import { SavedObjectsImportError } from '../errors'; diff --git a/src/core/server/saved_objects/import/resolve_import_errors.test.ts b/src/core/server/saved_objects/import/resolve_import_errors.test.ts index 2a228df80f2d3..08608978fecaa 100644 --- a/src/core/server/saved_objects/import/resolve_import_errors.test.ts +++ b/src/core/server/saved_objects/import/resolve_import_errors.test.ts @@ -23,15 +23,14 @@ import { import { Readable } from 'stream'; import { v4 as uuidv4 } from 'uuid'; -import { - SavedObjectsClientContract, - SavedObjectsType, +import type { SavedObject, SavedObjectsImportFailure, SavedObjectsImportRetry, SavedObjectReference, SavedObjectsImportWarning, -} from '../types'; +} from '@kbn/core-saved-objects-common'; +import { SavedObjectsClientContract, SavedObjectsType } from '../types'; import { savedObjectsClientMock } from '../../mocks'; import { ISavedObjectTypeRegistry, SavedObjectsImportHook } from '..'; import { typeRegistryMock } from '../saved_objects_type_registry.mock'; diff --git a/src/core/server/saved_objects/import/resolve_import_errors.ts b/src/core/server/saved_objects/import/resolve_import_errors.ts index 99daf2113e287..b9919ff1aa81c 100644 --- a/src/core/server/saved_objects/import/resolve_import_errors.ts +++ b/src/core/server/saved_objects/import/resolve_import_errors.ts @@ -7,14 +7,16 @@ */ import { Readable } from 'stream'; -import { SavedObject, SavedObjectsClientContract, SavedObjectsImportRetry } from '../types'; -import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry'; -import { +import type { + SavedObject, + SavedObjectsImportRetry, SavedObjectsImportFailure, - SavedObjectsImportHook, SavedObjectsImportResponse, SavedObjectsImportSuccess, -} from './types'; +} from '@kbn/core-saved-objects-common'; +import { SavedObjectsClientContract } from '../types'; +import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry'; +import { SavedObjectsImportHook } from './types'; import { collectSavedObjects, createObjectsFilter, diff --git a/src/core/server/saved_objects/import/saved_objects_importer.ts b/src/core/server/saved_objects/import/saved_objects_importer.ts index cc73b2d041edc..34f3692a2c0d4 100644 --- a/src/core/server/saved_objects/import/saved_objects_importer.ts +++ b/src/core/server/saved_objects/import/saved_objects_importer.ts @@ -6,12 +6,12 @@ * Side Public License, v 1. */ +import type { SavedObjectsImportResponse } from '@kbn/core-saved-objects-common'; import { SavedObjectsClientContract } from '../types'; import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry'; import { importSavedObjectsFromStream } from './import_saved_objects'; import { resolveSavedObjectsImportErrors } from './resolve_import_errors'; import { - SavedObjectsImportResponse, SavedObjectsImportOptions, SavedObjectsResolveImportErrorsOptions, SavedObjectsImportHook, diff --git a/src/core/server/saved_objects/index.ts b/src/core/server/saved_objects/index.ts index 434096193ff9f..7a68a8976fdf4 100644 --- a/src/core/server/saved_objects/index.ts +++ b/src/core/server/saved_objects/index.ts @@ -12,23 +12,11 @@ export { SavedObjectsImporter } from './import'; export type { ISavedObjectsImporter, - SavedObjectsImportAmbiguousConflictError, - SavedObjectsImportConflictError, - SavedObjectsImportFailure, - SavedObjectsImportMissingReferencesError, SavedObjectsImportOptions, - SavedObjectsImportResponse, - SavedObjectsImportRetry, - SavedObjectsImportSuccess, - SavedObjectsImportUnknownError, - SavedObjectsImportUnsupportedTypeError, SavedObjectsResolveImportErrorsOptions, SavedObjectsImportError, SavedObjectsImportHook, SavedObjectsImportHookResult, - SavedObjectsImportSimpleWarning, - SavedObjectsImportActionRequiredWarning, - SavedObjectsImportWarning, } from './import'; export type { @@ -87,7 +75,6 @@ export type { export { mergeSavedObjectMigrationMaps } from './migrations'; export type { - SavedObjectsNamespaceType, SavedObjectStatusMeta, SavedObjectsType, SavedObjectsTypeManagementDefinition, diff --git a/src/core/server/saved_objects/migrations/core/document_migrator.ts b/src/core/server/saved_objects/migrations/core/document_migrator.ts index fcee8da491496..75f037123a382 100644 --- a/src/core/server/saved_objects/migrations/core/document_migrator.ts +++ b/src/core/server/saved_objects/migrations/core/document_migrator.ts @@ -47,12 +47,12 @@ import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; import Semver from 'semver'; import type { Logger } from '@kbn/logging'; -import { SavedObjectUnsanitizedDoc } from '../../serialization'; -import { +import type { SavedObjectsMigrationVersion, SavedObjectsNamespaceType, - SavedObjectsType, -} from '../../types'; +} from '@kbn/core-saved-objects-common'; +import { SavedObjectUnsanitizedDoc } from '../../serialization'; +import { SavedObjectsType } from '../../types'; import { MigrationLogger } from './migration_logger'; import { TransformSavedObjectDocumentError } from '.'; import { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; diff --git a/src/core/server/saved_objects/migrations/initial_state.ts b/src/core/server/saved_objects/migrations/initial_state.ts index edf2b60a48145..dc8f5be7e4f36 100644 --- a/src/core/server/saved_objects/migrations/initial_state.ts +++ b/src/core/server/saved_objects/migrations/initial_state.ts @@ -9,8 +9,8 @@ import * as Option from 'fp-ts/Option'; import type { DocLinksServiceStart } from '@kbn/core-doc-links-server'; import type { Logger } from '@kbn/logging'; +import type { SavedObjectsMigrationVersion } from '@kbn/core-saved-objects-common'; import type { IndexMapping } from '../mappings'; -import type { SavedObjectsMigrationVersion } from '../../../types'; import type { SavedObjectsMigrationConfigType } from '../saved_objects_config'; import type { ISavedObjectTypeRegistry } from '../saved_objects_type_registry'; import type { InitState } from './state'; diff --git a/src/core/server/saved_objects/migrations/run_resilient_migrator.ts b/src/core/server/saved_objects/migrations/run_resilient_migrator.ts index 87618dcbab1c9..337947c33b989 100644 --- a/src/core/server/saved_objects/migrations/run_resilient_migrator.ts +++ b/src/core/server/saved_objects/migrations/run_resilient_migrator.ts @@ -9,8 +9,8 @@ import type { Logger } from '@kbn/logging'; import type { DocLinksServiceStart } from '@kbn/core-doc-links-server'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; +import type { SavedObjectsMigrationVersion } from '@kbn/core-saved-objects-common'; import { IndexMapping } from '../mappings'; -import type { SavedObjectsMigrationVersion } from '../types'; import type { TransformRawDocs } from './types'; import { MigrationResult } from './core'; import { next } from './next'; diff --git a/src/core/server/saved_objects/saved_objects_service.ts b/src/core/server/saved_objects/saved_objects_service.ts index 123550393f49b..2ce3acb63139e 100644 --- a/src/core/server/saved_objects/saved_objects_service.ts +++ b/src/core/server/saved_objects/saved_objects_service.ts @@ -18,6 +18,7 @@ import type { InternalElasticsearchServiceSetup, InternalElasticsearchServiceStart, } from '@kbn/core-elasticsearch-server-internal'; +import type { SavedObjectAttributes } from '@kbn/core-saved-objects-common'; import { SavedObjectsClient, SavedObjectsClientProvider, @@ -31,12 +32,7 @@ import { SavedObjectsMigrationConfigType, SavedObjectConfig, } from './saved_objects_config'; -import { - SavedObjectsClientContract, - SavedObjectsType, - SavedObjectStatusMeta, - SavedObjectAttributes, -} from './types'; +import { SavedObjectsClientContract, SavedObjectsType, SavedObjectStatusMeta } from './types'; import { ISavedObjectsRepository, SavedObjectsRepository } from './service/lib/repository'; import { SavedObjectsClientFactoryProvider, diff --git a/src/core/server/saved_objects/serialization/types.ts b/src/core/server/saved_objects/serialization/types.ts index 3956e2133e5a8..72def2def3e43 100644 --- a/src/core/server/saved_objects/serialization/types.ts +++ b/src/core/server/saved_objects/serialization/types.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedObjectsMigrationVersion, SavedObjectReference } from '../types'; +import { SavedObjectsMigrationVersion, SavedObjectReference } from '@kbn/core-saved-objects-common'; /** * A raw document as represented directly in the saved object index. diff --git a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts index fb6bd89f358f6..43f3bdaaa0921 100644 --- a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts +++ b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts @@ -7,9 +7,10 @@ */ import { isNotFoundFromUnsupportedServer } from '@kbn/core-elasticsearch-server-internal'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import type { SavedObjectsSerializer } from '../../serialization'; -import type { SavedObject, SavedObjectsBaseOptions } from '../../types'; +import type { SavedObjectsBaseOptions } from '../../types'; import { SavedObjectsErrorHelpers } from './errors'; import { findLegacyUrlAliases } from './legacy_url_aliases'; import { getRootFields } from './included_fields'; diff --git a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts index 44940cd0ae0d7..a9fd704247100 100644 --- a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts +++ b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts @@ -13,12 +13,13 @@ import { } from './internal_bulk_resolve.test.mock'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; import { LEGACY_URL_ALIAS_TYPE } from '../../object_types'; import { typeRegistryMock } from '../../saved_objects_type_registry.mock'; import { SavedObjectsSerializer } from '../../serialization'; import { SavedObjectsErrorHelpers } from './errors'; import { SavedObjectsBulkResolveObject } from '../saved_objects_client'; -import { SavedObject, SavedObjectsBaseOptions } from '../../types'; +import { SavedObjectsBaseOptions } from '../../types'; import { internalBulkResolve, InternalBulkResolveParams } from './internal_bulk_resolve'; import { SavedObjectsUtils } from './utils'; import { normalizeNamespace } from './internal_utils'; diff --git a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts index 96ea29486520b..aa44a320eecf7 100644 --- a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts +++ b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts @@ -9,6 +9,7 @@ import type { MgetResponseItem } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { isNotFoundFromUnsupportedServer } from '@kbn/core-elasticsearch-server-internal'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; import { CORE_USAGE_STATS_ID, CORE_USAGE_STATS_TYPE, @@ -17,7 +18,7 @@ import { import { LegacyUrlAlias, LEGACY_URL_ALIAS_TYPE } from '../../object_types'; import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import type { SavedObjectsRawDocSource, SavedObjectsSerializer } from '../../serialization'; -import type { SavedObject, SavedObjectsBaseOptions } from '../../types'; +import type { SavedObjectsBaseOptions } from '../../types'; import type { SavedObjectsBulkResolveObject, SavedObjectsResolveResponse, diff --git a/src/core/server/saved_objects/service/lib/internal_utils.ts b/src/core/server/saved_objects/service/lib/internal_utils.ts index abedcf53c781f..815290de79ba4 100644 --- a/src/core/server/saved_objects/service/lib/internal_utils.ts +++ b/src/core/server/saved_objects/service/lib/internal_utils.ts @@ -7,9 +7,9 @@ */ import type { Payload } from '@hapi/boom'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import type { SavedObjectsRawDoc, SavedObjectsRawDocSource } from '../../serialization'; -import type { SavedObject } from '../../types'; import { decodeRequestVersion, encodeHitVersion } from '../../version'; import { SavedObjectsErrorHelpers } from './errors'; import { ALL_NAMESPACES_STRING, SavedObjectsUtils } from './utils'; diff --git a/src/core/server/saved_objects/service/lib/repository.test.ts b/src/core/server/saved_objects/service/lib/repository.test.ts index c916953df2ad5..f4015968597cd 100644 --- a/src/core/server/saved_objects/service/lib/repository.test.ts +++ b/src/core/server/saved_objects/service/lib/repository.test.ts @@ -23,13 +23,8 @@ import { import type { Payload } from '@hapi/boom'; import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { schema } from '@kbn/config-schema'; -import { - SavedObjectsType, - SavedObject, - SavedObjectReference, - SavedObjectsBaseOptions, - SavedObjectsFindOptions, -} from '../../types'; +import type { SavedObject, SavedObjectReference } from '@kbn/core-saved-objects-common'; +import { SavedObjectsType, SavedObjectsBaseOptions, SavedObjectsFindOptions } from '../../types'; import type { SavedObjectsUpdateObjectsSpacesResponse } from './update_objects_spaces'; import { SavedObjectsDeleteByNamespaceOptions, diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index 6688b8ce18485..9d4ec529838ce 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -15,6 +15,7 @@ import { isSupportedEsServer, isNotFoundFromUnsupportedServer, } from '@kbn/core-elasticsearch-server-internal'; +import type { SavedObject, SavedObjectsMigrationVersion } from '@kbn/core-saved-objects-common'; import { getRootPropertiesObjects, IndexMapping } from '../../mappings'; import { ISavedObjectsPointInTimeFinder, @@ -61,10 +62,8 @@ import { } from '../saved_objects_client'; import { LEGACY_URL_ALIAS_TYPE } from '../../object_types'; import { - SavedObject, SavedObjectsBaseOptions, SavedObjectsFindOptions, - SavedObjectsMigrationVersion, MutatingOperationRefreshSetting, } from '../../types'; import { SavedObjectsTypeValidator } from '../../validation'; diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts index b8ffd0ad7e528..3b072490acf31 100644 --- a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts +++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts @@ -12,14 +12,11 @@ import intersection from 'lodash/intersection'; import type { Logger } from '@kbn/logging'; import { isNotFoundFromUnsupportedServer } from '@kbn/core-elasticsearch-server-internal'; +import type { SavedObjectError } from '@kbn/core-saved-objects-common'; import type { IndexMapping } from '../../mappings'; import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import type { SavedObjectsRawDocSource, SavedObjectsSerializer } from '../../serialization'; -import type { - MutatingOperationRefreshSetting, - SavedObjectError, - SavedObjectsBaseOptions, -} from '../../types'; +import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from '../../types'; import type { DecoratedError } from './errors'; import { SavedObjectsErrorHelpers } from './errors'; import { diff --git a/src/core/server/saved_objects/service/saved_objects_client.ts b/src/core/server/saved_objects/service/saved_objects_client.ts index ba40127958aab..f865da334757f 100644 --- a/src/core/server/saved_objects/service/saved_objects_client.ts +++ b/src/core/server/saved_objects/service/saved_objects_client.ts @@ -6,6 +6,12 @@ * Side Public License, v 1. */ +import type { + SavedObject, + SavedObjectError, + SavedObjectReference, + SavedObjectsMigrationVersion, +} from '@kbn/core-saved-objects-common'; import type { ISavedObjectsRepository, ISavedObjectsPointInTimeFinder, @@ -18,10 +24,6 @@ import type { SavedObjectsUpdateObjectsSpacesOptions, } from './lib'; import { - SavedObject, - SavedObjectError, - SavedObjectReference, - SavedObjectsMigrationVersion, SavedObjectsBaseOptions, MutatingOperationRefreshSetting, SavedObjectsFindOptions, diff --git a/src/core/types/index.ts b/src/core/types/index.ts index 005e5fb611cfb..edf51a8338e39 100644 --- a/src/core/types/index.ts +++ b/src/core/types/index.ts @@ -12,7 +12,16 @@ */ export * from './capabilities'; export * from './app_category'; -export * from './saved_objects'; +export type { + SavedObject, + SavedObjectsNamespaceType, + SavedObjectAttributeSingle, + SavedObjectAttribute, + SavedObjectAttributes, + SavedObjectError, + SavedObjectReference, + SavedObjectsMigrationVersion, +} from '@kbn/core-saved-objects-common'; export type { KibanaExecutionContext } from '@kbn/core-execution-context-common'; export type { UiSettingsType, From 9ea6b7051bb79e748c4fa1a82506e50e73a3cba8 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 20 Jul 2022 15:59:13 +0200 Subject: [PATCH 04/46] fix entrypoint exports --- src/core/server/index.ts | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/core/server/index.ts b/src/core/server/index.ts index c0e450ebde765..710f027a03906 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -283,6 +283,21 @@ export { mergeSavedObjectMigrationMaps, } from './saved_objects'; +export type { + SavedObjectsImportConflictError, + SavedObjectsImportAmbiguousConflictError, + SavedObjectsImportFailure, + SavedObjectsImportMissingReferencesError, + SavedObjectsImportResponse, + SavedObjectsImportRetry, + SavedObjectsImportSuccess, + SavedObjectsImportUnknownError, + SavedObjectsImportUnsupportedTypeError, + SavedObjectsNamespaceType, + SavedObjectsImportSimpleWarning, + SavedObjectsImportActionRequiredWarning, + SavedObjectsImportWarning, +} from '@kbn/core-saved-objects-common'; export type { SavedObjectsBulkCreateObject, SavedObjectsBulkGetObject, @@ -308,16 +323,7 @@ export type { SavedObjectsExportExcludedObject, SavedObjectsFindResult, SavedObjectsFindResponse, - SavedObjectsImportConflictError, - SavedObjectsImportAmbiguousConflictError, - SavedObjectsImportFailure, - SavedObjectsImportMissingReferencesError, SavedObjectsImportOptions, - SavedObjectsImportResponse, - SavedObjectsImportRetry, - SavedObjectsImportSuccess, - SavedObjectsImportUnknownError, - SavedObjectsImportUnsupportedTypeError, SavedObjectMigrationContext, SavedObjectsMigrationLogger, SavedObjectsOpenPointInTimeOptions, @@ -356,7 +362,6 @@ export type { SavedObjectsTypeMappingDefinition, SavedObjectsMappingProperties, ISavedObjectTypeRegistry, - SavedObjectsNamespaceType, SavedObjectsType, SavedObjectsTypeManagementDefinition, SavedObjectMigrationMap, @@ -374,9 +379,6 @@ export type { SavedObjectsImportError, SavedObjectsImportHook, SavedObjectsImportHookResult, - SavedObjectsImportSimpleWarning, - SavedObjectsImportActionRequiredWarning, - SavedObjectsImportWarning, SavedObjectsValidationMap, SavedObjectsValidationSpec, SavedObjectsRequestHandlerContext, From 715621cc4917fbce8d3e725ab3b3529188726ecf Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 20 Jul 2022 16:50:10 +0200 Subject: [PATCH 05/46] fix external import --- x-pack/plugins/maps/public/maps_vis_type_alias.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/x-pack/plugins/maps/public/maps_vis_type_alias.ts b/x-pack/plugins/maps/public/maps_vis_type_alias.ts index 911e886a8199e..5a58902dda53b 100644 --- a/x-pack/plugins/maps/public/maps_vis_type_alias.ts +++ b/x-pack/plugins/maps/public/maps_vis_type_alias.ts @@ -7,8 +7,7 @@ import { i18n } from '@kbn/i18n'; import type { VisualizationsSetup, VisualizationStage } from '@kbn/visualizations-plugin/public'; -import type { SimpleSavedObject } from '@kbn/core/public'; -import type { SavedObject } from '@kbn/core/types/saved_objects'; +import type { SimpleSavedObject, SavedObject } from '@kbn/core/public'; import type { MapSavedObjectAttributes } from '../common/map_saved_object_type'; import { APP_ID, From ea107a8c68fcb49ca422febcfae13ed07b6fcdee Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 20 Jul 2022 17:18:10 +0200 Subject: [PATCH 06/46] create explicit ISavedObjectsRepository interface --- .../saved_objects/service/lib/repository.ts | 730 +++++++++++------- 1 file changed, 445 insertions(+), 285 deletions(-) diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index 9d4ec529838ce..e6197ca56ec36 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -93,11 +93,13 @@ import { collectMultiNamespaceReferences, SavedObjectsCollectMultiNamespaceReferencesObject, SavedObjectsCollectMultiNamespaceReferencesOptions, + SavedObjectsCollectMultiNamespaceReferencesResponse, } from './collect_multi_namespace_references'; import { updateObjectsSpaces, SavedObjectsUpdateObjectsSpacesObject, SavedObjectsUpdateObjectsSpacesOptions, + SavedObjectsUpdateObjectsSpacesResponse, } from './update_objects_spaces'; import { getIndexForType } from './get_index_for_type'; import { @@ -160,7 +162,429 @@ export const DEFAULT_RETRY_COUNT = 3; * * @public */ -export type ISavedObjectsRepository = Pick; +export interface ISavedObjectsRepository { + /** + * Persists an object + * + * @param {string} type + * @param {object} attributes + * @param {object} [options={}] + * @property {string} [options.id] - force id on creation, not recommended + * @property {boolean} [options.overwrite=false] + * @property {object} [options.migrationVersion=undefined] + * @property {string} [options.namespace] + * @property {array} [options.references=[]] - [{ name, type, id }] + * @returns {promise} - { id, type, version, attributes } + */ + create( + type: string, + attributes: T, + options?: SavedObjectsCreateOptions + ): Promise>; + + /** + * Creates multiple documents at once + * + * @param {array} objects - [{ type, id, attributes, references, migrationVersion }] + * @param {object} [options={}] + * @property {boolean} [options.overwrite=false] - overwrites existing documents + * @property {string} [options.namespace] + * @returns {promise} - {saved_objects: [[{ id, type, version, references, attributes, error: { message } }]} + */ + bulkCreate( + objects: Array>, + options?: SavedObjectsCreateOptions + ): Promise>; + + /** + * Check what conflicts will result when creating a given array of saved objects. This includes "unresolvable conflicts", which are + * multi-namespace objects that exist in a different namespace; such conflicts cannot be resolved/overwritten. + */ + checkConflicts( + objects: SavedObjectsCheckConflictsObject[], + options?: SavedObjectsBaseOptions + ): Promise; + + /** + * Deletes an object + * + * @param {string} type + * @param {string} id + * @param {object} [options={}] + * @property {string} [options.namespace] + * @returns {promise} + */ + delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>; + + /** + * Deletes all objects from the provided namespace. + * + * @param {string} namespace + * @returns {promise} - { took, timed_out, total, deleted, batches, version_conflicts, noops, retries, failures } + */ + deleteByNamespace( + namespace: string, + options?: SavedObjectsDeleteByNamespaceOptions + ): Promise; + + /** + * @param {object} [options={}] + * @property {(string|Array)} [options.type] + * @property {string} [options.search] + * @property {string} [options.defaultSearchOperator] + * @property {Array} [options.searchFields] - see Elasticsearch Simple Query String + * Query field argument for more information + * @property {integer} [options.page=1] + * @property {integer} [options.perPage=20] + * @property {Array} [options.searchAfter] + * @property {string} [options.sortField] + * @property {string} [options.sortOrder] + * @property {Array} [options.fields] + * @property {string} [options.namespace] + * @property {object} [options.hasReference] - { type, id } + * @property {string} [options.pit] + * @property {string} [options.preference] + * @returns {promise} - { saved_objects: [{ id, type, version, attributes }], total, per_page, page } + */ + find( + options: SavedObjectsFindOptions + ): Promise>; + + /** + * Returns an array of objects by id + * + * @param {array} objects - an array of objects containing id, type and optionally fields + * @param {object} [options={}] + * @property {string} [options.namespace] + * @returns {promise} - { saved_objects: [{ id, type, version, attributes }] } + * @example + * + * bulkGet([ + * { id: 'one', type: 'config' }, + * { id: 'foo', type: 'index-pattern' } + * ]) + */ + bulkGet( + objects: SavedObjectsBulkGetObject[], + options?: SavedObjectsBaseOptions + ): Promise>; + + /** + * Resolves an array of objects by id, using any legacy URL aliases if they exist + * + * @param {array} objects - an array of objects containing id, type + * @param {object} [options={}] + * @property {string} [options.namespace] + * @returns {promise} - { resolved_objects: [{ saved_object, outcome }] } + * @example + * + * bulkResolve([ + * { id: 'one', type: 'config' }, + * { id: 'foo', type: 'index-pattern' } + * ]) + */ + bulkResolve( + objects: SavedObjectsBulkResolveObject[], + options?: SavedObjectsBaseOptions + ): Promise>; + + /** + * Gets a single object + * + * @param {string} type + * @param {string} id + * @param {object} [options={}] + * @property {string} [options.namespace] + * @returns {promise} - { id, type, version, attributes } + */ + get( + type: string, + id: string, + options?: SavedObjectsBaseOptions + ): Promise>; + + /** + * Resolves a single object, using any legacy URL alias if it exists + * + * @param {string} type + * @param {string} id + * @param {object} [options={}] + * @property {string} [options.namespace] + * @returns {promise} - { saved_object, outcome } + */ + resolve( + type: string, + id: string, + options?: SavedObjectsBaseOptions + ): Promise>; + + /** + * Updates an object + * + * @param {string} type + * @param {string} id + * @param {object} [options={}] + * @property {string} options.version - ensures version matches that of persisted object + * @property {string} [options.namespace] + * @property {array} [options.references] - [{ name, type, id }] + * @returns {promise} + */ + update( + type: string, + id: string, + attributes: Partial, + options?: SavedObjectsUpdateOptions + ): Promise>; + + /** + * Gets all references and transitive references of the given objects. Ignores any object and/or reference that is not a multi-namespace + * type. + * + * @param objects The objects to get the references for. + */ + collectMultiNamespaceReferences( + objects: SavedObjectsCollectMultiNamespaceReferencesObject[], + options?: SavedObjectsCollectMultiNamespaceReferencesOptions + ): Promise; + + /** + * Updates one or more objects to add and/or remove them from specified spaces. + * + * @param objects + * @param spacesToAdd + * @param spacesToRemove + * @param options + */ + updateObjectsSpaces( + objects: SavedObjectsUpdateObjectsSpacesObject[], + spacesToAdd: string[], + spacesToRemove: string[], + options?: SavedObjectsUpdateObjectsSpacesOptions + ): Promise; + + /** + * Updates multiple objects in bulk + * + * @param {array} objects - [{ type, id, attributes, options: { version, namespace } references }] + * @property {string} options.version - ensures version matches that of persisted object + * @property {string} [options.namespace] + * @returns {promise} - {saved_objects: [[{ id, type, version, references, attributes, error: { message } }]} + */ + bulkUpdate( + objects: Array>, + options?: SavedObjectsBulkUpdateOptions + ): Promise>; + + /** + * Updates all objects containing a reference to the given {type, id} tuple to remove the said reference. + * + * @remarks Will throw a conflict error if the `update_by_query` operation returns any failure. In that case + * some references might have been removed, and some were not. It is the caller's responsibility + * to handle and fix this situation if it was to happen. + */ + removeReferencesTo( + type: string, + id: string, + options?: SavedObjectsRemoveReferencesToOptions + ): Promise; + + /** + * Increments all the specified counter fields (by one by default). Creates the document + * if one doesn't exist for the given id. + * + * @remarks + * When supplying a field name like `stats.api.counter` the field name will + * be used as-is to create a document like: + * `{attributes: {'stats.api.counter': 1}}` + * It will not create a nested structure like: + * `{attributes: {stats: {api: {counter: 1}}}}` + * + * When using incrementCounter for collecting usage data, you need to ensure + * that usage collection happens on a best-effort basis and doesn't + * negatively affect your plugin or users. See https://github.com/elastic/kibana/blob/main/src/plugins/usage_collection/README.mdx#tracking-interactions-with-incrementcounter) + * + * @example + * ```ts + * const repository = coreStart.savedObjects.createInternalRepository(); + * + * // Initialize all fields to 0 + * repository + * .incrementCounter('dashboard_counter_type', 'counter_id', [ + * 'stats.apiCalls', + * 'stats.sampleDataInstalled', + * ], {initialize: true}); + * + * // Increment the apiCalls field counter + * repository + * .incrementCounter('dashboard_counter_type', 'counter_id', [ + * 'stats.apiCalls', + * ]) + * + * // Increment the apiCalls field counter by 4 + * repository + * .incrementCounter('dashboard_counter_type', 'counter_id', [ + * { fieldName: 'stats.apiCalls' incrementBy: 4 }, + * ]) + * + * // Initialize the document with arbitrary fields if not present + * repository.incrementCounter<{ appId: string }>( + * 'dashboard_counter_type', + * 'counter_id', + * [ 'stats.apiCalls'], + * { upsertAttributes: { appId: 'myId' } } + * ) + * ``` + * + * @param type - The type of saved object whose fields should be incremented + * @param id - The id of the document whose fields should be incremented + * @param counterFields - An array of field names to increment or an array of {@link SavedObjectsIncrementCounterField} + * @param options - {@link SavedObjectsIncrementCounterOptions} + * @returns The saved object after the specified fields were incremented + */ + incrementCounter( + type: string, + id: string, + counterFields: Array, + options?: SavedObjectsIncrementCounterOptions + ): Promise>; + + /** + * Opens a Point In Time (PIT) against the indices for the specified Saved Object types. + * The returned `id` can then be passed to `SavedObjects.find` to search against that PIT. + * + * Only use this API if you have an advanced use case that's not solved by the + * {@link SavedObjectsRepository.createPointInTimeFinder} method. + * + * @example + * ```ts + * const { id } = await savedObjectsClient.openPointInTimeForType( + * type: 'visualization', + * { keepAlive: '5m' }, + * ); + * const page1 = await savedObjectsClient.find({ + * type: 'visualization', + * sortField: 'updated_at', + * sortOrder: 'asc', + * pit: { id, keepAlive: '2m' }, + * }); + * const lastHit = page1.saved_objects[page1.saved_objects.length - 1]; + * const page2 = await savedObjectsClient.find({ + * type: 'visualization', + * sortField: 'updated_at', + * sortOrder: 'asc', + * pit: { id: page1.pit_id }, + * searchAfter: lastHit.sort, + * }); + * await savedObjectsClient.closePointInTime(page2.pit_id); + * ``` + * + * @param {string|Array} type + * @param {object} [options] - {@link SavedObjectsOpenPointInTimeOptions} + * @property {string} [options.keepAlive] + * @property {string} [options.preference] + * @returns {promise} - { id: string } + */ + openPointInTimeForType( + type: string | string[], + options?: SavedObjectsOpenPointInTimeOptions + ): Promise; + + /** + * Closes a Point In Time (PIT) by ID. This simply proxies the request to ES + * via the Elasticsearch client, and is included in the Saved Objects Client + * as a convenience for consumers who are using `openPointInTimeForType`. + * + * Only use this API if you have an advanced use case that's not solved by the + * {@link SavedObjectsRepository.createPointInTimeFinder} method. + * + * @remarks + * While the `keepAlive` that is provided will cause a PIT to automatically close, + * it is highly recommended to explicitly close a PIT when you are done with it + * in order to avoid consuming unneeded resources in Elasticsearch. + * + * @example + * ```ts + * const repository = coreStart.savedObjects.createInternalRepository(); + * + * const { id } = await repository.openPointInTimeForType( + * type: 'index-pattern', + * { keepAlive: '2m' }, + * ); + * + * const response = await repository.find({ + * type: 'index-pattern', + * search: 'foo*', + * sortField: 'name', + * sortOrder: 'desc', + * pit: { + * id: 'abc123', + * keepAlive: '2m', + * }, + * searchAfter: [1234, 'abcd'], + * }); + * + * await repository.closePointInTime(response.pit_id); + * ``` + * + * @param {string} id + * @param {object} [options] - {@link SavedObjectsClosePointInTimeOptions} + * @returns {promise} - {@link SavedObjectsClosePointInTimeResponse} + */ + closePointInTime( + id: string, + options?: SavedObjectsClosePointInTimeOptions + ): Promise; + + /** + * Returns a {@link ISavedObjectsPointInTimeFinder} to help page through + * large sets of saved objects. We strongly recommend using this API for + * any `find` queries that might return more than 1000 saved objects, + * however this API is only intended for use in server-side "batch" + * processing of objects where you are collecting all objects in memory + * or streaming them back to the client. + * + * Do NOT use this API in a route handler to facilitate paging through + * saved objects on the client-side unless you are streaming all of the + * results back to the client at once. Because the returned generator is + * stateful, you cannot rely on subsequent http requests retrieving new + * pages from the same Kibana server in multi-instance deployments. + * + * This generator wraps calls to {@link SavedObjectsRepository.find} and + * iterates over multiple pages of results using `_pit` and `search_after`. + * This will open a new Point-In-Time (PIT), and continue paging until a + * set of results is received that's smaller than the designated `perPage`. + * + * Once you have retrieved all of the results you need, it is recommended + * to call `close()` to clean up the PIT and prevent Elasticsearch from + * consuming resources unnecessarily. This is only required if you are + * done iterating and have not yet paged through all of the results: the + * PIT will automatically be closed for you once you reach the last page + * of results, or if the underlying call to `find` fails for any reason. + * + * @example + * ```ts + * const findOptions: SavedObjectsCreatePointInTimeFinderOptions = { + * type: 'visualization', + * search: 'foo*', + * perPage: 100, + * }; + * + * const finder = savedObjectsClient.createPointInTimeFinder(findOptions); + * + * const responses: SavedObjectFindResponse[] = []; + * for await (const response of finder.find()) { + * responses.push(...response); + * if (doneSearching) { + * await finder.close(); + * } + * } + * ``` + */ + createPointInTimeFinder( + findOptions: SavedObjectsCreatePointInTimeFinderOptions, + dependencies?: SavedObjectsCreatePointInTimeFinderDependencies + ): ISavedObjectsPointInTimeFinder; +} /** * @public @@ -208,7 +632,7 @@ function isMgetDoc(doc?: estypes.MgetResponseItem): doc is estypes.GetG /** * @public */ -export class SavedObjectsRepository { +export class SavedObjectsRepository implements ISavedObjectsRepository { private _migrator: IKibanaMigrator; private _index: string; private _mappings: IndexMapping; @@ -294,17 +718,7 @@ export class SavedObjectsRepository { } /** - * Persists an object - * - * @param {string} type - * @param {object} attributes - * @param {object} [options={}] - * @property {string} [options.id] - force id on creation, not recommended - * @property {boolean} [options.overwrite=false] - * @property {object} [options.migrationVersion=undefined] - * @property {string} [options.namespace] - * @property {array} [options.references=[]] - [{ name, type, id }] - * @returns {promise} - { id, type, version, attributes } + * {@inheritDoc ISavedObjectsRepository.create} */ public async create( type: string, @@ -417,13 +831,7 @@ export class SavedObjectsRepository { } /** - * Creates multiple documents at once - * - * @param {array} objects - [{ type, id, attributes, references, migrationVersion }] - * @param {object} [options={}] - * @property {boolean} [options.overwrite=false] - overwrites existing documents - * @property {string} [options.namespace] - * @returns {promise} - {saved_objects: [[{ id, type, version, references, attributes, error: { message } }]} + * {@inheritDoc ISavedObjectsRepository.bulkCreate} */ async bulkCreate( objects: Array>, @@ -639,8 +1047,7 @@ export class SavedObjectsRepository { } /** - * Check what conflicts will result when creating a given array of saved objects. This includes "unresolvable conflicts", which are - * multi-namespace objects that exist in a different namespace; such conflicts cannot be resolved/overwritten. + * {@inheritDoc ISavedObjectsRepository.checkConflicts} */ async checkConflicts( objects: SavedObjectsCheckConflictsObject[] = [], @@ -732,13 +1139,7 @@ export class SavedObjectsRepository { } /** - * Deletes an object - * - * @param {string} type - * @param {string} id - * @param {object} [options={}] - * @property {string} [options.namespace] - * @returns {promise} + * {@inheritDoc ISavedObjectsRepository.delete} */ async delete(type: string, id: string, options: SavedObjectsDeleteOptions = {}): Promise<{}> { if (!this._allowedTypes.includes(type)) { @@ -831,10 +1232,7 @@ export class SavedObjectsRepository { } /** - * Deletes all objects from the provided namespace. - * - * @param {string} namespace - * @returns {promise} - { took, timed_out, total, deleted, batches, version_conflicts, noops, retries, failures } + * {@inheritDoc ISavedObjectsRepository.deleteByNamespace} */ async deleteByNamespace( namespace: string, @@ -894,23 +1292,7 @@ export class SavedObjectsRepository { } /** - * @param {object} [options={}] - * @property {(string|Array)} [options.type] - * @property {string} [options.search] - * @property {string} [options.defaultSearchOperator] - * @property {Array} [options.searchFields] - see Elasticsearch Simple Query String - * Query field argument for more information - * @property {integer} [options.page=1] - * @property {integer} [options.perPage=20] - * @property {Array} [options.searchAfter] - * @property {string} [options.sortField] - * @property {string} [options.sortOrder] - * @property {Array} [options.fields] - * @property {string} [options.namespace] - * @property {object} [options.hasReference] - { type, id } - * @property {string} [options.pit] - * @property {string} [options.preference] - * @returns {promise} - { saved_objects: [{ id, type, version, attributes }], total, per_page, page } + * {@inheritDoc ISavedObjectsRepository.find} */ async find( options: SavedObjectsFindOptions @@ -1073,18 +1455,7 @@ export class SavedObjectsRepository { } /** - * Returns an array of objects by id - * - * @param {array} objects - an array of objects containing id, type and optionally fields - * @param {object} [options={}] - * @property {string} [options.namespace] - * @returns {promise} - { saved_objects: [{ id, type, version, attributes }] } - * @example - * - * bulkGet([ - * { id: 'one', type: 'config' }, - * { id: 'foo', type: 'index-pattern' } - * ]) + * {@inheritDoc ISavedObjectsRepository.bulkGet} */ async bulkGet( objects: SavedObjectsBulkGetObject[] = [], @@ -1191,18 +1562,7 @@ export class SavedObjectsRepository { } /** - * Resolves an array of objects by id, using any legacy URL aliases if they exist - * - * @param {array} objects - an array of objects containing id, type - * @param {object} [options={}] - * @property {string} [options.namespace] - * @returns {promise} - { resolved_objects: [{ saved_object, outcome }] } - * @example - * - * bulkResolve([ - * { id: 'one', type: 'config' }, - * { id: 'foo', type: 'index-pattern' } - * ]) + * {@inheritDoc ISavedObjectsRepository.bulkResolve} */ async bulkResolve( objects: SavedObjectsBulkResolveObject[], @@ -1234,13 +1594,7 @@ export class SavedObjectsRepository { } /** - * Gets a single object - * - * @param {string} type - * @param {string} id - * @param {object} [options={}] - * @property {string} [options.namespace] - * @returns {promise} - { id, type, version, attributes } + * {@inheritDoc ISavedObjectsRepository.get} */ async get( type: string, @@ -1276,13 +1630,7 @@ export class SavedObjectsRepository { } /** - * Resolves a single object, using any legacy URL alias if it exists - * - * @param {string} type - * @param {string} id - * @param {object} [options={}] - * @property {string} [options.namespace] - * @returns {promise} - { saved_object, outcome } + * {@inheritDoc ISavedObjectsRepository.resolve} */ async resolve( type: string, @@ -1307,15 +1655,7 @@ export class SavedObjectsRepository { } /** - * Updates an object - * - * @param {string} type - * @param {string} id - * @param {object} [options={}] - * @property {string} options.version - ensures version matches that of persisted object - * @property {string} [options.namespace] - * @property {array} [options.references] - [{ name, type, id }] - * @returns {promise} + * {@inheritDoc ISavedObjectsRepository.update} */ async update( type: string, @@ -1439,10 +1779,7 @@ export class SavedObjectsRepository { } /** - * Gets all references and transitive references of the given objects. Ignores any object and/or reference that is not a multi-namespace - * type. - * - * @param objects The objects to get the references for. + * {@inheritDoc ISavedObjectsRepository.collectMultiNamespaceReferences} */ async collectMultiNamespaceReferences( objects: SavedObjectsCollectMultiNamespaceReferencesObject[], @@ -1461,12 +1798,7 @@ export class SavedObjectsRepository { } /** - * Updates one or more objects to add and/or remove them from specified spaces. - * - * @param objects - * @param spacesToAdd - * @param spacesToRemove - * @param options + * {@inheritDoc ISavedObjectsRepository.updateObjectsSpaces} */ async updateObjectsSpaces( objects: SavedObjectsUpdateObjectsSpacesObject[], @@ -1490,12 +1822,7 @@ export class SavedObjectsRepository { } /** - * Updates multiple objects in bulk - * - * @param {array} objects - [{ type, id, attributes, options: { version, namespace } references }] - * @property {string} options.version - ensures version matches that of persisted object - * @property {string} [options.namespace] - * @returns {promise} - {saved_objects: [[{ id, type, version, references, attributes, error: { message } }]} + * {@inheritDoc ISavedObjectsRepository.bulkUpdate} */ async bulkUpdate( objects: Array>, @@ -1712,11 +2039,7 @@ export class SavedObjectsRepository { } /** - * Updates all objects containing a reference to the given {type, id} tuple to remove the said reference. - * - * @remarks Will throw a conflict error if the `update_by_query` operation returns any failure. In that case - * some references might have been removed, and some were not. It is the caller's responsibility - * to handle and fix this situation if it was to happen. + * {@inheritDoc ISavedObjectsRepository.removeReferencesTo} */ async removeReferencesTo( type: string, @@ -1781,57 +2104,7 @@ export class SavedObjectsRepository { } /** - * Increments all the specified counter fields (by one by default). Creates the document - * if one doesn't exist for the given id. - * - * @remarks - * When supplying a field name like `stats.api.counter` the field name will - * be used as-is to create a document like: - * `{attributes: {'stats.api.counter': 1}}` - * It will not create a nested structure like: - * `{attributes: {stats: {api: {counter: 1}}}}` - * - * When using incrementCounter for collecting usage data, you need to ensure - * that usage collection happens on a best-effort basis and doesn't - * negatively affect your plugin or users. See https://github.com/elastic/kibana/blob/main/src/plugins/usage_collection/README.mdx#tracking-interactions-with-incrementcounter) - * - * @example - * ```ts - * const repository = coreStart.savedObjects.createInternalRepository(); - * - * // Initialize all fields to 0 - * repository - * .incrementCounter('dashboard_counter_type', 'counter_id', [ - * 'stats.apiCalls', - * 'stats.sampleDataInstalled', - * ], {initialize: true}); - * - * // Increment the apiCalls field counter - * repository - * .incrementCounter('dashboard_counter_type', 'counter_id', [ - * 'stats.apiCalls', - * ]) - * - * // Increment the apiCalls field counter by 4 - * repository - * .incrementCounter('dashboard_counter_type', 'counter_id', [ - * { fieldName: 'stats.apiCalls' incrementBy: 4 }, - * ]) - * - * // Initialize the document with arbitrary fields if not present - * repository.incrementCounter<{ appId: string }>( - * 'dashboard_counter_type', - * 'counter_id', - * [ 'stats.apiCalls'], - * { upsertAttributes: { appId: 'myId' } } - * ) - * ``` - * - * @param type - The type of saved object whose fields should be incremented - * @param id - The id of the document whose fields should be incremented - * @param counterFields - An array of field names to increment or an array of {@link SavedObjectsIncrementCounterField} - * @param options - {@link SavedObjectsIncrementCounterOptions} - * @returns The saved object after the specified fields were incremented + * {@inheritDoc ISavedObjectsRepository.incrementCounter} */ async incrementCounter( type: string, @@ -2001,40 +2274,7 @@ export class SavedObjectsRepository { } /** - * Opens a Point In Time (PIT) against the indices for the specified Saved Object types. - * The returned `id` can then be passed to `SavedObjects.find` to search against that PIT. - * - * Only use this API if you have an advanced use case that's not solved by the - * {@link SavedObjectsRepository.createPointInTimeFinder} method. - * - * @example - * ```ts - * const { id } = await savedObjectsClient.openPointInTimeForType( - * type: 'visualization', - * { keepAlive: '5m' }, - * ); - * const page1 = await savedObjectsClient.find({ - * type: 'visualization', - * sortField: 'updated_at', - * sortOrder: 'asc', - * pit: { id, keepAlive: '2m' }, - * }); - * const lastHit = page1.saved_objects[page1.saved_objects.length - 1]; - * const page2 = await savedObjectsClient.find({ - * type: 'visualization', - * sortField: 'updated_at', - * sortOrder: 'asc', - * pit: { id: page1.pit_id }, - * searchAfter: lastHit.sort, - * }); - * await savedObjectsClient.closePointInTime(page2.pit_id); - * ``` - * - * @param {string|Array} type - * @param {object} [options] - {@link SavedObjectsOpenPointInTimeOptions} - * @property {string} [options.keepAlive] - * @property {string} [options.preference] - * @returns {promise} - { id: string } + * {@inheritDoc ISavedObjectsRepository.openPointInTimeForType} */ async openPointInTimeForType( type: string | string[], @@ -2071,45 +2311,7 @@ export class SavedObjectsRepository { } /** - * Closes a Point In Time (PIT) by ID. This simply proxies the request to ES - * via the Elasticsearch client, and is included in the Saved Objects Client - * as a convenience for consumers who are using `openPointInTimeForType`. - * - * Only use this API if you have an advanced use case that's not solved by the - * {@link SavedObjectsRepository.createPointInTimeFinder} method. - * - * @remarks - * While the `keepAlive` that is provided will cause a PIT to automatically close, - * it is highly recommended to explicitly close a PIT when you are done with it - * in order to avoid consuming unneeded resources in Elasticsearch. - * - * @example - * ```ts - * const repository = coreStart.savedObjects.createInternalRepository(); - * - * const { id } = await repository.openPointInTimeForType( - * type: 'index-pattern', - * { keepAlive: '2m' }, - * ); - * - * const response = await repository.find({ - * type: 'index-pattern', - * search: 'foo*', - * sortField: 'name', - * sortOrder: 'desc', - * pit: { - * id: 'abc123', - * keepAlive: '2m', - * }, - * searchAfter: [1234, 'abcd'], - * }); - * - * await repository.closePointInTime(response.pit_id); - * ``` - * - * @param {string} id - * @param {object} [options] - {@link SavedObjectsClosePointInTimeOptions} - * @returns {promise} - {@link SavedObjectsClosePointInTimeResponse} + * {@inheritDoc ISavedObjectsRepository.closePointInTime} */ async closePointInTime( id: string, @@ -2121,49 +2323,7 @@ export class SavedObjectsRepository { } /** - * Returns a {@link ISavedObjectsPointInTimeFinder} to help page through - * large sets of saved objects. We strongly recommend using this API for - * any `find` queries that might return more than 1000 saved objects, - * however this API is only intended for use in server-side "batch" - * processing of objects where you are collecting all objects in memory - * or streaming them back to the client. - * - * Do NOT use this API in a route handler to facilitate paging through - * saved objects on the client-side unless you are streaming all of the - * results back to the client at once. Because the returned generator is - * stateful, you cannot rely on subsequent http requests retrieving new - * pages from the same Kibana server in multi-instance deployments. - * - * This generator wraps calls to {@link SavedObjectsRepository.find} and - * iterates over multiple pages of results using `_pit` and `search_after`. - * This will open a new Point-In-Time (PIT), and continue paging until a - * set of results is received that's smaller than the designated `perPage`. - * - * Once you have retrieved all of the results you need, it is recommended - * to call `close()` to clean up the PIT and prevent Elasticsearch from - * consuming resources unnecessarily. This is only required if you are - * done iterating and have not yet paged through all of the results: the - * PIT will automatically be closed for you once you reach the last page - * of results, or if the underlying call to `find` fails for any reason. - * - * @example - * ```ts - * const findOptions: SavedObjectsCreatePointInTimeFinderOptions = { - * type: 'visualization', - * search: 'foo*', - * perPage: 100, - * }; - * - * const finder = savedObjectsClient.createPointInTimeFinder(findOptions); - * - * const responses: SavedObjectFindResponse[] = []; - * for await (const response of finder.find()) { - * responses.push(...response); - * if (doneSearching) { - * await finder.close(); - * } - * } - * ``` + * {@inheritDoc ISavedObjectsRepository.createPointInTimeFinder} */ createPointInTimeFinder( findOptions: SavedObjectsCreatePointInTimeFinderOptions, From 5b45973393454deb4fa1bab67fa7160dae5b2444 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 20 Jul 2022 17:19:42 +0200 Subject: [PATCH 07/46] fix another external usage --- x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts b/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts index 796c4312eb2ea..81d37c8d34608 100644 --- a/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts +++ b/x-pack/plugins/apm/server/routes/settings/apm_indices/route.ts @@ -77,7 +77,7 @@ const saveApmIndicesRoute = createApmServerRoute({ handler: async ( resources ): Promise< - import('./../../../../../../../src/core/types/saved_objects').SavedObject<{}> + import('./../../../../../../../src/core/types').SavedObject<{}> > => { const { params, context } = resources; const { body } = params; From db0a2eb0873f7bf40c0bade9259577c44c4fe7f0 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Wed, 20 Jul 2022 17:35:53 +0200 Subject: [PATCH 08/46] rewrite browser exports --- src/core/public/index.ts | 19 +++++++++++-------- src/core/public/saved_objects/index.ts | 23 ----------------------- 2 files changed, 11 insertions(+), 31 deletions(-) diff --git a/src/core/public/index.ts b/src/core/public/index.ts index ccde84105ea89..68da5ad6b5f14 100644 --- a/src/core/public/index.ts +++ b/src/core/public/index.ts @@ -127,8 +127,8 @@ export type { NavigateToUrlOptions, } from './application'; +// TODO: check if can be exported as type. export { SimpleSavedObject } from './saved_objects'; -export type { ResolvedSimpleSavedObject } from './saved_objects'; export type { SavedObjectsBatchResponse, SavedObjectsBulkCreateObject, @@ -141,17 +141,22 @@ export type { SavedObjectsFindResponsePublic, SavedObjectsResolveResponse, SavedObjectsUpdateOptions, + SavedObjectsBaseOptions, + SavedObjectsFindOptions, + SavedObjectsFindOptionsReference, + SavedObjectsClientContract, + SavedObjectReferenceWithContext, + SavedObjectsCollectMultiNamespaceReferencesResponse, + ResolvedSimpleSavedObject, +} from './saved_objects'; +export type { SavedObject, SavedObjectAttribute, SavedObjectAttributes, SavedObjectAttributeSingle, SavedObjectError, SavedObjectReference, - SavedObjectsBaseOptions, - SavedObjectsFindOptions, - SavedObjectsFindOptionsReference, SavedObjectsMigrationVersion, - SavedObjectsClientContract, SavedObjectsImportResponse, SavedObjectsImportSuccess, SavedObjectsImportConflictError, @@ -165,9 +170,7 @@ export type { SavedObjectsImportSimpleWarning, SavedObjectsImportActionRequiredWarning, SavedObjectsImportWarning, - SavedObjectReferenceWithContext, - SavedObjectsCollectMultiNamespaceReferencesResponse, -} from './saved_objects'; +} from '@kbn/core-saved-objects-common'; export type { HttpHeadersInit, diff --git a/src/core/public/saved_objects/index.ts b/src/core/public/saved_objects/index.ts index 1880948225010..76675d3707993 100644 --- a/src/core/public/saved_objects/index.ts +++ b/src/core/public/saved_objects/index.ts @@ -27,31 +27,8 @@ export type { SavedObjectsBaseOptions, SavedObjectsFindOptions, SavedObjectsFindOptionsReference, - SavedObjectsMigrationVersion, - SavedObjectsImportResponse, - SavedObjectsImportSuccess, - SavedObjectsImportConflictError, - SavedObjectsImportAmbiguousConflictError, - SavedObjectsImportUnsupportedTypeError, - SavedObjectsImportMissingReferencesError, - SavedObjectsImportUnknownError, - SavedObjectsImportFailure, - SavedObjectsImportRetry, - SavedObjectsNamespaceType, - SavedObjectsImportSimpleWarning, - SavedObjectsImportActionRequiredWarning, - SavedObjectsImportWarning, SavedObjectReferenceWithContext, SavedObjectsCollectMultiNamespaceReferencesResponse, SavedObjectsBulkResolveObject, SavedObjectsResolveResponse, } from '../../server'; - -export type { - SavedObject, - SavedObjectAttribute, - SavedObjectAttributes, - SavedObjectAttributeSingle, - SavedObjectError, - SavedObjectReference, -} from '../../types'; From cfa2a7162d7da8f624d0db0f5eb44dc0de1a9a89 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 09:26:50 +0200 Subject: [PATCH 09/46] create explicit SavedObjectsClientContract interface --- .../service/saved_objects_client.ts | 337 +++++++++++++----- src/core/server/saved_objects/types.ts | 65 +--- 2 files changed, 255 insertions(+), 147 deletions(-) diff --git a/src/core/server/saved_objects/service/saved_objects_client.ts b/src/core/server/saved_objects/service/saved_objects_client.ts index f865da334757f..aab310beab214 100644 --- a/src/core/server/saved_objects/service/saved_objects_client.ts +++ b/src/core/server/saved_objects/service/saved_objects_client.ts @@ -29,6 +29,7 @@ import { SavedObjectsFindOptions, } from '../types'; import { SavedObjectsErrorHelpers } from './lib/errors'; +import { SavedObjectsUpdateObjectsSpacesResponse } from './lib'; /** * @@ -434,20 +435,68 @@ export interface SavedObjectsClosePointInTimeResponse { } /** + * Saved Objects is Kibana's data persisentence mechanism allowing plugins to + * use Elasticsearch for storing plugin state. + * + * ## SavedObjectsClient errors + * + * Since the SavedObjectsClient has its hands in everything we + * are a little paranoid about the way we present errors back to + * to application code. Ideally, all errors will be either: + * + * 1. Caused by bad implementation (ie. undefined is not a function) and + * as such unpredictable + * 2. An error that has been classified and decorated appropriately + * by the decorators in {@link SavedObjectsErrorHelpers} + * + * Type 1 errors are inevitable, but since all expected/handle-able errors + * should be Type 2 the `isXYZError()` helpers exposed at + * `SavedObjectsErrorHelpers` should be used to understand and manage error + * responses from the `SavedObjectsClient`. + * + * Type 2 errors are decorated versions of the source error, so if + * the elasticsearch client threw an error it will be decorated based + * on its type. That means that rather than looking for `error.body.error.type` or + * doing substring checks on `error.body.error.reason`, just use the helpers to + * understand the meaning of the error: + * + * ```js + * if (SavedObjectsErrorHelpers.isNotFoundError(error)) { + * // handle 404 + * } + * + * if (SavedObjectsErrorHelpers.isNotAuthorizedError(error)) { + * // 401 handling should be automatic, but in case you wanted to know + * } + * + * // always rethrow the error unless you handle it + * throw error; + * ``` + * + * ### 404s from missing index + * + * From the perspective of application code and APIs the SavedObjectsClient is + * a black box that persists objects. One of the internal details that users have + * no control over is that we use an elasticsearch index for persistence and that + * index might be missing. + * + * At the time of writing we are in the process of transitioning away from the + * operating assumption that the SavedObjects index is always available. Part of + * this transition is handling errors resulting from an index missing. These used + * to trigger a 500 error in most cases, and in others cause 404s with different + * error messages. + * + * From my (Spencer) perspective, a 404 from the SavedObjectsApi is a 404; The + * object the request/call was targeting could not be found. This is why #14141 + * takes special care to ensure that 404 errors are generic and don't distinguish + * between index missing or document missing. + * + * See {@link SavedObjectsClient} + * See {@link SavedObjectsErrorHelpers} * * @public */ -export class SavedObjectsClient { - public static errors = SavedObjectsErrorHelpers; - public errors = SavedObjectsErrorHelpers; - - private _repository: ISavedObjectsRepository; - - /** @internal */ - constructor(repository: ISavedObjectsRepository) { - this._repository = repository; - } - +export interface SavedObjectsClientContract { /** * Persists a SavedObject * @@ -455,9 +504,11 @@ export class SavedObjectsClient { * @param attributes * @param options */ - async create(type: string, attributes: T, options?: SavedObjectsCreateOptions) { - return await this._repository.create(type, attributes, options); - } + create( + type: string, + attributes: T, + options?: SavedObjectsCreateOptions + ): Promise>; /** * Persists multiple documents batched together as a single request @@ -465,12 +516,10 @@ export class SavedObjectsClient { * @param objects * @param options */ - async bulkCreate( + bulkCreate( objects: Array>, options?: SavedObjectsCreateOptions - ) { - return await this._repository.bulkCreate(objects, options); - } + ): Promise>; /** * Check what conflicts will result when creating a given array of saved objects. This includes "unresolvable conflicts", which are @@ -479,12 +528,10 @@ export class SavedObjectsClient { * @param objects * @param options */ - async checkConflicts( - objects: SavedObjectsCheckConflictsObject[] = [], - options: SavedObjectsBaseOptions = {} - ): Promise { - return await this._repository.checkConflicts(objects, options); - } + checkConflicts( + objects: SavedObjectsCheckConflictsObject[], + options?: SavedObjectsBaseOptions + ): Promise; /** * Deletes a SavedObject @@ -493,20 +540,16 @@ export class SavedObjectsClient { * @param id * @param options */ - async delete(type: string, id: string, options: SavedObjectsDeleteOptions = {}) { - return await this._repository.delete(type, id, options); - } + delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>; /** * Find all SavedObjects matching the search query * * @param options */ - async find( + find( options: SavedObjectsFindOptions - ): Promise> { - return await this._repository.find(options); - } + ): Promise>; /** * Returns an array of objects by id @@ -519,12 +562,10 @@ export class SavedObjectsClient { * { id: 'foo', type: 'index-pattern' } * ]) */ - async bulkGet( - objects: SavedObjectsBulkGetObject[] = [], - options: SavedObjectsBaseOptions = {} - ): Promise> { - return await this._repository.bulkGet(objects, options); - } + bulkGet( + objects: SavedObjectsBulkGetObject[], + options?: SavedObjectsBaseOptions + ): Promise>; /** * Retrieves a single object @@ -533,13 +574,11 @@ export class SavedObjectsClient { * @param id - The ID of the SavedObject to retrieve * @param options */ - async get( + get( type: string, id: string, - options: SavedObjectsBaseOptions = {} - ): Promise> { - return await this._repository.get(type, id, options); - } + options?: SavedObjectsBaseOptions + ): Promise>; /** * Resolves an array of objects by id, using any legacy URL aliases if they exist @@ -556,12 +595,10 @@ export class SavedObjectsClient { * outcome is that "exactMatch" is the default outcome, and the outcome only changes if an alias is found. This behavior is unique to * `bulkResolve`; the regular `resolve` API will throw an error instead. */ - async bulkResolve( + bulkResolve( objects: SavedObjectsBulkResolveObject[], options?: SavedObjectsBaseOptions - ): Promise> { - return await this._repository.bulkResolve(objects, options); - } + ): Promise>; /** * Resolves a single object, using any legacy URL alias if it exists @@ -570,13 +607,11 @@ export class SavedObjectsClient { * @param id - The ID of the SavedObject to retrieve * @param options */ - async resolve( + resolve( type: string, id: string, - options: SavedObjectsBaseOptions = {} - ): Promise> { - return await this._repository.resolve(type, id, options); - } + options?: SavedObjectsBaseOptions + ): Promise>; /** * Updates an SavedObject @@ -585,37 +620,31 @@ export class SavedObjectsClient { * @param id * @param options */ - async update( + update( type: string, id: string, attributes: Partial, - options: SavedObjectsUpdateOptions = {} - ): Promise> { - return await this._repository.update(type, id, attributes, options); - } + options?: SavedObjectsUpdateOptions + ): Promise>; /** * Bulk Updates multiple SavedObject at once * * @param objects */ - async bulkUpdate( + bulkUpdate( objects: Array>, options?: SavedObjectsBulkUpdateOptions - ): Promise> { - return await this._repository.bulkUpdate(objects, options); - } + ): Promise>; /** * Updates all objects containing a reference to the given {type, id} tuple to remove the said reference. */ - async removeReferencesTo( + removeReferencesTo( type: string, id: string, options?: SavedObjectsRemoveReferencesToOptions - ) { - return await this._repository.removeReferencesTo(type, id, options); - } + ): Promise; /** * Opens a Point In Time (PIT) against the indices for the specified Saved Object types. @@ -625,12 +654,10 @@ export class SavedObjectsClient { * Only use this API if you have an advanced use case that's not solved by the * {@link SavedObjectsClient.createPointInTimeFinder} method. */ - async openPointInTimeForType( + openPointInTimeForType( type: string | string[], - options: SavedObjectsOpenPointInTimeOptions = {} - ) { - return await this._repository.openPointInTimeForType(type, options); - } + options?: SavedObjectsOpenPointInTimeOptions + ): Promise; /** * Closes a Point In Time (PIT) by ID. This simply proxies the request to ES via the @@ -640,9 +667,10 @@ export class SavedObjectsClient { * Only use this API if you have an advanced use case that's not solved by the * {@link SavedObjectsClient.createPointInTimeFinder} method. */ - async closePointInTime(id: string, options?: SavedObjectsClosePointInTimeOptions) { - return await this._repository.closePointInTime(id, options); - } + closePointInTime( + id: string, + options?: SavedObjectsClosePointInTimeOptions + ): Promise; /** * Returns a {@link ISavedObjectsPointInTimeFinder} to help page through @@ -692,13 +720,7 @@ export class SavedObjectsClient { createPointInTimeFinder( findOptions: SavedObjectsCreatePointInTimeFinderOptions, dependencies?: SavedObjectsCreatePointInTimeFinderDependencies - ): ISavedObjectsPointInTimeFinder { - return this._repository.createPointInTimeFinder(findOptions, { - client: this, - // Include dependencies last so that SO client wrappers have their settings applied. - ...dependencies, - }); - } + ): ISavedObjectsPointInTimeFinder; /** * Gets all references and transitive references of the listed objects. Ignores any object that is not a multi-namespace type. @@ -706,12 +728,10 @@ export class SavedObjectsClient { * @param objects * @param options */ - async collectMultiNamespaceReferences( + collectMultiNamespaceReferences( objects: SavedObjectsCollectMultiNamespaceReferencesObject[], options?: SavedObjectsCollectMultiNamespaceReferencesOptions - ): Promise { - return await this._repository.collectMultiNamespaceReferences(objects, options); - } + ): Promise; /** * Updates one or more objects to add and/or remove them from specified spaces. @@ -721,6 +741,157 @@ export class SavedObjectsClient { * @param spacesToRemove * @param options */ + updateObjectsSpaces( + objects: SavedObjectsUpdateObjectsSpacesObject[], + spacesToAdd: string[], + spacesToRemove: string[], + options?: SavedObjectsUpdateObjectsSpacesOptions + ): Promise; +} + +/** + * Core internal implementation of {@link SavedObjectsClientContract} + * @internal + */ +export class SavedObjectsClient implements SavedObjectsClientContract { + public static errors = SavedObjectsErrorHelpers; + public errors = SavedObjectsErrorHelpers; + + private _repository: ISavedObjectsRepository; + + /** @internal */ + constructor(repository: ISavedObjectsRepository) { + this._repository = repository; + } + + /** {@inheritDoc SavedObjectsClientContract.create} */ + async create(type: string, attributes: T, options?: SavedObjectsCreateOptions) { + return await this._repository.create(type, attributes, options); + } + + /** {@inheritDoc SavedObjectsClientContract.bulkCreate} */ + async bulkCreate( + objects: Array>, + options?: SavedObjectsCreateOptions + ) { + return await this._repository.bulkCreate(objects, options); + } + + /** {@inheritDoc SavedObjectsClientContract.checkConflicts} */ + async checkConflicts( + objects: SavedObjectsCheckConflictsObject[] = [], + options: SavedObjectsBaseOptions = {} + ): Promise { + return await this._repository.checkConflicts(objects, options); + } + + /** {@inheritDoc SavedObjectsClientContract.delete} */ + async delete(type: string, id: string, options: SavedObjectsDeleteOptions = {}) { + return await this._repository.delete(type, id, options); + } + + /** {@inheritDoc SavedObjectsClientContract.find} */ + async find( + options: SavedObjectsFindOptions + ): Promise> { + return await this._repository.find(options); + } + + /** {@inheritDoc SavedObjectsClientContract.bulkGet} */ + async bulkGet( + objects: SavedObjectsBulkGetObject[] = [], + options: SavedObjectsBaseOptions = {} + ): Promise> { + return await this._repository.bulkGet(objects, options); + } + + /** {@inheritDoc SavedObjectsClientContract.get} */ + async get( + type: string, + id: string, + options: SavedObjectsBaseOptions = {} + ): Promise> { + return await this._repository.get(type, id, options); + } + + /** {@inheritDoc SavedObjectsClientContract.bulkResolve} */ + async bulkResolve( + objects: SavedObjectsBulkResolveObject[], + options?: SavedObjectsBaseOptions + ): Promise> { + return await this._repository.bulkResolve(objects, options); + } + + /** {@inheritDoc SavedObjectsClientContract.resolve} */ + async resolve( + type: string, + id: string, + options: SavedObjectsBaseOptions = {} + ): Promise> { + return await this._repository.resolve(type, id, options); + } + + /** {@inheritDoc SavedObjectsClientContract.update} */ + async update( + type: string, + id: string, + attributes: Partial, + options: SavedObjectsUpdateOptions = {} + ): Promise> { + return await this._repository.update(type, id, attributes, options); + } + + /** {@inheritDoc SavedObjectsClientContract.bulkUpdate} */ + async bulkUpdate( + objects: Array>, + options?: SavedObjectsBulkUpdateOptions + ): Promise> { + return await this._repository.bulkUpdate(objects, options); + } + + /** {@inheritDoc SavedObjectsClientContract.removeReferencesTo} */ + async removeReferencesTo( + type: string, + id: string, + options?: SavedObjectsRemoveReferencesToOptions + ) { + return await this._repository.removeReferencesTo(type, id, options); + } + + /** {@inheritDoc SavedObjectsClientContract.openPointInTimeForType} */ + async openPointInTimeForType( + type: string | string[], + options: SavedObjectsOpenPointInTimeOptions = {} + ) { + return await this._repository.openPointInTimeForType(type, options); + } + + /** {@inheritDoc SavedObjectsClientContract.closePointInTime} */ + async closePointInTime(id: string, options?: SavedObjectsClosePointInTimeOptions) { + return await this._repository.closePointInTime(id, options); + } + + /** {@inheritDoc SavedObjectsClientContract.createPointInTimeFinder} */ + createPointInTimeFinder( + findOptions: SavedObjectsCreatePointInTimeFinderOptions, + dependencies?: SavedObjectsCreatePointInTimeFinderDependencies + ): ISavedObjectsPointInTimeFinder { + return this._repository.createPointInTimeFinder(findOptions, { + client: this, + // Include dependencies last so that SO client wrappers have their settings applied. + ...dependencies, + }); + } + + /** {@inheritDoc SavedObjectsClientContract.collectMultiNamespaceReferences} */ + async collectMultiNamespaceReferences( + objects: SavedObjectsCollectMultiNamespaceReferencesObject[], + options?: SavedObjectsCollectMultiNamespaceReferencesOptions + ): Promise { + return await this._repository.collectMultiNamespaceReferences(objects, options); + } + + /** {@inheritDoc SavedObjectsClientContract.updateObjectsSpaces} */ async updateObjectsSpaces( objects: SavedObjectsUpdateObjectsSpacesObject[], spacesToAdd: string[], diff --git a/src/core/server/saved_objects/types.ts b/src/core/server/saved_objects/types.ts index a67c0808328cb..5105e063d0cd1 100644 --- a/src/core/server/saved_objects/types.ts +++ b/src/core/server/saved_objects/types.ts @@ -9,7 +9,6 @@ import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server'; import type { SavedObject, SavedObjectsNamespaceType } from '@kbn/core-saved-objects-common'; -import { SavedObjectsClient } from './service/saved_objects_client'; import { SavedObjectsTypeMappingDefinition } from './mappings'; import { SavedObjectMigrationMap } from './migrations'; import { SavedObjectsExportTransform } from './export'; @@ -146,69 +145,7 @@ export interface SavedObjectsBaseOptions { */ export type MutatingOperationRefreshSetting = boolean | 'wait_for'; -/** - * Saved Objects is Kibana's data persisentence mechanism allowing plugins to - * use Elasticsearch for storing plugin state. - * - * ## SavedObjectsClient errors - * - * Since the SavedObjectsClient has its hands in everything we - * are a little paranoid about the way we present errors back to - * to application code. Ideally, all errors will be either: - * - * 1. Caused by bad implementation (ie. undefined is not a function) and - * as such unpredictable - * 2. An error that has been classified and decorated appropriately - * by the decorators in {@link SavedObjectsErrorHelpers} - * - * Type 1 errors are inevitable, but since all expected/handle-able errors - * should be Type 2 the `isXYZError()` helpers exposed at - * `SavedObjectsErrorHelpers` should be used to understand and manage error - * responses from the `SavedObjectsClient`. - * - * Type 2 errors are decorated versions of the source error, so if - * the elasticsearch client threw an error it will be decorated based - * on its type. That means that rather than looking for `error.body.error.type` or - * doing substring checks on `error.body.error.reason`, just use the helpers to - * understand the meaning of the error: - * - * ```js - * if (SavedObjectsErrorHelpers.isNotFoundError(error)) { - * // handle 404 - * } - * - * if (SavedObjectsErrorHelpers.isNotAuthorizedError(error)) { - * // 401 handling should be automatic, but in case you wanted to know - * } - * - * // always rethrow the error unless you handle it - * throw error; - * ``` - * - * ### 404s from missing index - * - * From the perspective of application code and APIs the SavedObjectsClient is - * a black box that persists objects. One of the internal details that users have - * no control over is that we use an elasticsearch index for persistence and that - * index might be missing. - * - * At the time of writing we are in the process of transitioning away from the - * operating assumption that the SavedObjects index is always available. Part of - * this transition is handling errors resulting from an index missing. These used - * to trigger a 500 error in most cases, and in others cause 404s with different - * error messages. - * - * From my (Spencer) perspective, a 404 from the SavedObjectsApi is a 404; The - * object the request/call was targeting could not be found. This is why #14141 - * takes special care to ensure that 404 errors are generic and don't distinguish - * between index missing or document missing. - * - * See {@link SavedObjectsClient} - * See {@link SavedObjectsErrorHelpers} - * - * @public - */ -export type SavedObjectsClientContract = Pick; +export type { SavedObjectsClientContract } from './service/saved_objects_client'; /** * @public From 62a7fd8ba1d1e8873be7aaffb3f512a5597ff9bd Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 10:25:30 +0200 Subject: [PATCH 10/46] move client/repository types to @kbn/core-saved-objects-api-server --- package.json | 2 + packages/BUILD.bazel | 2 + .../core-saved-objects-api-server/BUILD.bazel | 99 +++ .../core-saved-objects-api-server/README.md | 5 + .../jest.config.js | 13 + .../package.json | 7 + .../src/apis/base.ts | 32 + .../src/apis/bulk_create.ts | 49 ++ .../src/apis/bulk_get.ts | 29 + .../src/apis/bulk_resolve.ts | 26 + .../src/apis/bulk_update.ts | 48 ++ .../src/apis/check_conflicts.ts | 30 + .../src/apis/close_point_in_time.ts | 29 + .../apis/collect_multinamespace_references.ts | 77 ++ .../src/apis/create.ts | 57 ++ .../src/apis/create_point_in_time_finder.ts | 47 ++ .../src/apis/delete.ts | 20 + .../src/apis/delete_by_namespace.ts | 18 + .../src/apis/find.ts | 173 +++++ .../src/apis/increment_counter.ts | 43 ++ .../src/apis/index.ts | 73 ++ .../src/apis/open_point_in_time_for_type.ts | 40 + .../src/apis/remove_references_to.ts | 27 + .../src/apis/resolve.ts | 45 ++ .../src/apis/update.ts | 43 ++ .../src/apis/update_objects_spaces.ts | 69 ++ .../src/index.ts | 54 ++ .../src/saved_objects_client.ts | 359 +++++++++ .../src/saved_objects_repository.ts | 476 ++++++++++++ .../tsconfig.json | 18 + .../lib/collect_multi_namespace_references.ts | 66 -- .../service/lib/point_in_time_finder.ts | 36 +- .../saved_objects/service/lib/repository.ts | 469 +----------- .../service/lib/update_objects_spaces.ts | 57 -- .../service/saved_objects_client.ts | 717 ------------------ src/core/server/saved_objects/types.ts | 111 --- yarn.lock | 8 + 37 files changed, 2022 insertions(+), 1452 deletions(-) create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/BUILD.bazel create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/README.md create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/jest.config.js create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/package.json create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/base.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_create.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_get.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_resolve.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_update.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/check_conflicts.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/close_point_in_time.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/collect_multinamespace_references.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/create.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/create_point_in_time_finder.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/delete.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/delete_by_namespace.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/find.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/increment_counter.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/index.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/open_point_in_time_for_type.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/remove_references_to.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/resolve.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/update.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/apis/update_objects_spaces.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/index.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/saved_objects_client.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/src/saved_objects_repository.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-server/tsconfig.json diff --git a/package.json b/package.json index 04001b79ed03a..3c45ff1ba6126 100644 --- a/package.json +++ b/package.json @@ -216,6 +216,7 @@ "@kbn/core-preboot-server": "link:bazel-bin/packages/core/preboot/core-preboot-server", "@kbn/core-preboot-server-internal": "link:bazel-bin/packages/core/preboot/core-preboot-server-internal", "@kbn/core-preboot-server-mocks": "link:bazel-bin/packages/core/preboot/core-preboot-server-mocks", + "@kbn/core-saved-objects-api-server": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-server", "@kbn/core-saved-objects-common": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-common", "@kbn/core-test-helpers-http-setup-browser": "link:bazel-bin/packages/core/test-helpers/core-test-helpers-http-setup-browser", "@kbn/core-theme-browser": "link:bazel-bin/packages/core/theme/core-theme-browser", @@ -812,6 +813,7 @@ "@types/kbn__core-preboot-server-internal": "link:bazel-bin/packages/core/preboot/core-preboot-server-internal/npm_module_types", "@types/kbn__core-preboot-server-mocks": "link:bazel-bin/packages/core/preboot/core-preboot-server-mocks/npm_module_types", "@types/kbn__core-public-internal-base": "link:bazel-bin/packages/core/public/internal-base/npm_module_types", + "@types/kbn__core-saved-objects-api-server": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-server/npm_module_types", "@types/kbn__core-saved-objects-common": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-common/npm_module_types", "@types/kbn__core-server-internal-base": "link:bazel-bin/packages/core/server/internal-base/npm_module_types", "@types/kbn__core-test-helpers-http-setup-browser": "link:bazel-bin/packages/core/test-helpers/core-test-helpers-http-setup-browser/npm_module_types", diff --git a/packages/BUILD.bazel b/packages/BUILD.bazel index e6c2b998af76b..6d4f44f2f7e1a 100644 --- a/packages/BUILD.bazel +++ b/packages/BUILD.bazel @@ -83,6 +83,7 @@ filegroup( "//packages/core/preboot/core-preboot-server-internal:build", "//packages/core/preboot/core-preboot-server-mocks:build", "//packages/core/preboot/core-preboot-server:build", + "//packages/core/saved-objects/core-saved-objects-api-server:build", "//packages/core/saved-objects/core-saved-objects-common:build", "//packages/core/test-helpers/core-test-helpers-http-setup-browser:build", "//packages/core/theme/core-theme-browser-internal:build", @@ -300,6 +301,7 @@ filegroup( "//packages/core/preboot/core-preboot-server-internal:build_types", "//packages/core/preboot/core-preboot-server-mocks:build_types", "//packages/core/preboot/core-preboot-server:build_types", + "//packages/core/saved-objects/core-saved-objects-api-server:build_types", "//packages/core/saved-objects/core-saved-objects-common:build_types", "//packages/core/test-helpers/core-test-helpers-http-setup-browser:build_types", "//packages/core/theme/core-theme-browser-internal:build_types", diff --git a/packages/core/saved-objects/core-saved-objects-api-server/BUILD.bazel b/packages/core/saved-objects/core-saved-objects-api-server/BUILD.bazel new file mode 100644 index 0000000000000..31c7374fd44d9 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/BUILD.bazel @@ -0,0 +1,99 @@ +load("@npm//@bazel/typescript:index.bzl", "ts_config") +load("@build_bazel_rules_nodejs//:index.bzl", "js_library") +load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project") + +PKG_DIRNAME = "core-saved-objects-api-server" +PKG_REQUIRE_NAME = "@kbn/core-saved-objects-api-server" + +SOURCE_FILES = glob( + [ + "src/**/*.ts", + ], + exclude = [ + "**/*.test.*", + "**/*.stories.*", + ], +) + +SRCS = SOURCE_FILES + +filegroup( + name = "srcs", + srcs = SRCS, +) + +NPM_MODULE_EXTRA_FILES = [ + "package.json", +] + +RUNTIME_DEPS = [ +] + +TYPES_DEPS = [ + "@npm//@types/node", + "@npm//@types/jest", + "@npm//@elastic/elasticsearch", + "//packages/core/saved-objects/core-saved-objects-common:npm_module_types" +] + +jsts_transpiler( + name = "target_node", + srcs = SRCS, + build_pkg_name = package_name(), +) + +ts_config( + name = "tsconfig", + src = "tsconfig.json", + deps = [ + "//:tsconfig.base.json", + "//:tsconfig.bazel.json", + ], +) + +ts_project( + name = "tsc_types", + args = ['--pretty'], + srcs = SRCS, + deps = TYPES_DEPS, + declaration = True, + declaration_map = True, + emit_declaration_only = True, + out_dir = "target_types", + root_dir = "src", + tsconfig = ":tsconfig", +) + +js_library( + name = PKG_DIRNAME, + srcs = NPM_MODULE_EXTRA_FILES, + deps = RUNTIME_DEPS + [":target_node"], + package_name = PKG_REQUIRE_NAME, + visibility = ["//visibility:public"], +) + +pkg_npm( + name = "npm_module", + deps = [":" + PKG_DIRNAME], +) + +filegroup( + name = "build", + srcs = [":npm_module"], + visibility = ["//visibility:public"], +) + +pkg_npm_types( + name = "npm_module_types", + srcs = SRCS, + deps = [":tsc_types"], + package_name = PKG_REQUIRE_NAME, + tsconfig = ":tsconfig", + visibility = ["//visibility:public"], +) + +filegroup( + name = "build_types", + srcs = [":npm_module_types"], + visibility = ["//visibility:public"], +) diff --git a/packages/core/saved-objects/core-saved-objects-api-server/README.md b/packages/core/saved-objects/core-saved-objects-api-server/README.md new file mode 100644 index 0000000000000..8a2da90f7337d --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/README.md @@ -0,0 +1,5 @@ +# @kbn/core-saved-objects-api-server + +This package contains the public types for core's server-side savedObjects client (and repository) APIs. + + diff --git a/packages/core/saved-objects/core-saved-objects-api-server/jest.config.js b/packages/core/saved-objects/core-saved-objects-api-server/jest.config.js new file mode 100644 index 0000000000000..c598c13ec8f15 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/jest.config.js @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +module.exports = { + preset: '@kbn/test/jest_node', + rootDir: '../../../..', + roots: ['/packages/core/saved-objects/core-saved-objects-api-server'], +}; diff --git a/packages/core/saved-objects/core-saved-objects-api-server/package.json b/packages/core/saved-objects/core-saved-objects-api-server/package.json new file mode 100644 index 0000000000000..971c97fad93bb --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/package.json @@ -0,0 +1,7 @@ +{ + "name": "@kbn/core-saved-objects-api-server", + "private": true, + "version": "1.0.0", + "main": "./target_node/index.js", + "license": "SSPL-1.0 OR Elastic License 2.0" +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/base.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/base.ts new file mode 100644 index 0000000000000..e02a4142448ef --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/base.ts @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObject } from '@kbn/core-saved-objects-common'; + +/** + * Base options used by most of the savedObject APIs. + * @public + */ +export interface SavedObjectsBaseOptions { + /** Specify the namespace for this operation */ + namespace?: string; +} + +/** + * Elasticsearch Refresh setting for mutating operation + * @public + */ +export type MutatingOperationRefreshSetting = boolean | 'wait_for'; + +/** + * + * @public + */ +export interface SavedObjectsBulkResponse { + saved_objects: Array>; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_create.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_create.ts new file mode 100644 index 0000000000000..735564cfec63d --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_create.ts @@ -0,0 +1,49 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { + SavedObjectReference, + SavedObjectsMigrationVersion, +} from '@kbn/core-saved-objects-common'; + +/** + * + * @public + */ +export interface SavedObjectsBulkCreateObject { + id?: string; + type: string; + attributes: T; + version?: string; + references?: SavedObjectReference[]; + /** {@inheritDoc SavedObjectsMigrationVersion} */ + migrationVersion?: SavedObjectsMigrationVersion; + /** + * A semver value that is used when upgrading objects between Kibana versions. If undefined, this will be automatically set to the current + * Kibana version when the object is created. If this is set to a non-semver value, or it is set to a semver value greater than the + * current Kibana version, it will result in an error. + * + * @remarks + * Do not attempt to set this manually. It should only be used if you retrieved an existing object that had the `coreMigrationVersion` + * field set and you want to create it again. + */ + coreMigrationVersion?: string; + /** Optional ID of the original saved object, if this object's `id` was regenerated */ + originId?: string; + /** + * Optional initial namespaces for the object to be created in. If this is defined, it will supersede the namespace ID that is in + * {@link SavedObjectsCreateOptions}. + * + * * For shareable object types (registered with `namespaceType: 'multiple'`): this option can be used to specify one or more spaces, + * including the "All spaces" identifier (`'*'`). + * * For isolated object types (registered with `namespaceType: 'single'` or `namespaceType: 'multiple-isolated'`): this option can only + * be used to specify a single space, and the "All spaces" identifier (`'*'`) is not allowed. + * * For global object types (registered with `namespaceType: 'agnostic'`): this option cannot be used. + */ + initialNamespaces?: string[]; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_get.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_get.ts new file mode 100644 index 0000000000000..fbbe6c958594d --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_get.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +/** + * + * @public + */ +export interface SavedObjectsBulkGetObject { + id: string; + type: string; + /** SavedObject fields to include in the response */ + fields?: string[]; + /** + * Optional namespace(s) for the object to be retrieved in. If this is defined, it will supersede the namespace ID that is in the + * top-level options. + * + * * For shareable object types (registered with `namespaceType: 'multiple'`): this option can be used to specify one or more spaces, + * including the "All spaces" identifier (`'*'`). + * * For isolated object types (registered with `namespaceType: 'single'` or `namespaceType: 'multiple-isolated'`): this option can only + * be used to specify a single space, and the "All spaces" identifier (`'*'`) is not allowed. + * * For global object types (registered with `namespaceType: 'agnostic'`): this option cannot be used. + */ + namespaces?: string[]; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_resolve.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_resolve.ts new file mode 100644 index 0000000000000..b52c8caf26e82 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_resolve.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectsResolveResponse } from './resolve'; + +/** + * + * @public + */ +export interface SavedObjectsBulkResolveObject { + id: string; + type: string; +} + +/** + * + * @public + */ +export interface SavedObjectsBulkResolveResponse { + resolved_objects: Array>; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_update.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_update.ts new file mode 100644 index 0000000000000..102e46809b55e --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/bulk_update.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from './base'; +import type { SavedObjectsUpdateOptions, SavedObjectsUpdateResponse } from './update'; + +/** + * + * @public + */ +export interface SavedObjectsBulkUpdateObject + extends Pick, 'version' | 'references'> { + /** The ID of this Saved Object, guaranteed to be unique for all objects of the same `type` */ + id: string; + /** The type of this Saved Object. Each plugin can define it's own custom Saved Object types. */ + type: string; + /** {@inheritdoc SavedObjectAttributes} */ + attributes: Partial; + /** + * Optional namespace string to use when searching for this object. If this is defined, it will supersede the namespace ID that is in + * {@link SavedObjectsBulkUpdateOptions}. + * + * Note: the default namespace's string representation is `'default'`, and its ID representation is `undefined`. + **/ + namespace?: string; +} + +/** + * + * @public + */ +export interface SavedObjectsBulkUpdateOptions extends SavedObjectsBaseOptions { + /** The Elasticsearch Refresh setting for this operation */ + refresh?: MutatingOperationRefreshSetting; +} + +/** + * + * @public + */ +export interface SavedObjectsBulkUpdateResponse { + saved_objects: Array>; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/check_conflicts.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/check_conflicts.ts new file mode 100644 index 0000000000000..38d1c281b1000 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/check_conflicts.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectError } from '@kbn/core-saved-objects-common'; + +/** + * + * @public + */ +export interface SavedObjectsCheckConflictsObject { + id: string; + type: string; +} + +/** + * + * @public + */ +export interface SavedObjectsCheckConflictsResponse { + errors: Array<{ + id: string; + type: string; + error: SavedObjectError; + }>; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/close_point_in_time.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/close_point_in_time.ts new file mode 100644 index 0000000000000..16348155003d2 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/close_point_in_time.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectsBaseOptions } from './base'; + +/** + * @public + */ +export type SavedObjectsClosePointInTimeOptions = SavedObjectsBaseOptions; + +/** + * @public + */ +export interface SavedObjectsClosePointInTimeResponse { + /** + * If true, all search contexts associated with the PIT id are + * successfully closed. + */ + succeeded: boolean; + /** + * The number of search contexts that have been successfully closed. + */ + num_freed: number; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/collect_multinamespace_references.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/collect_multinamespace_references.ts new file mode 100644 index 0000000000000..59bfd4144a8c1 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/collect_multinamespace_references.ts @@ -0,0 +1,77 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectsBaseOptions } from './base'; + +/** + * An object to collect references for. It must be a multi-namespace type (in other words, the object type must be registered with the + * `namespaceType: 'multiple'` or `namespaceType: 'multiple-isolated'` option). + * + * Note: if options.purpose is 'updateObjectsSpaces', it must be a shareable type (in other words, the object type must be registered with + * the `namespaceType: 'multiple'`). + * + * @public + */ +export interface SavedObjectsCollectMultiNamespaceReferencesObject { + id: string; + type: string; +} + +/** + * Options for collecting references. + * + * @public + */ +export interface SavedObjectsCollectMultiNamespaceReferencesOptions + extends SavedObjectsBaseOptions { + /** Optional purpose used to determine filtering and authorization checks; default is 'collectMultiNamespaceReferences' */ + purpose?: 'collectMultiNamespaceReferences' | 'updateObjectsSpaces'; +} + +/** + * A returned input object or one of its references, with additional context. + * + * @public + */ +export interface SavedObjectReferenceWithContext { + /** The type of the referenced object */ + type: string; + /** The ID of the referenced object */ + id: string; + /** The origin ID of the referenced object (if it has one) */ + originId?: string; + /** The space(s) that the referenced object exists in */ + spaces: string[]; + /** + * References to this object; note that this does not contain _all inbound references everywhere for this object_, it only contains + * inbound references for the scope of this operation + */ + inboundReferences: Array<{ + /** The type of the object that has the inbound reference */ + type: string; + /** The ID of the object that has the inbound reference */ + id: string; + /** The name of the inbound reference */ + name: string; + }>; + /** Whether or not this object or reference is missing */ + isMissing?: boolean; + /** The space(s) that legacy URL aliases matching this type/id exist in */ + spacesWithMatchingAliases?: string[]; + /** The space(s) that objects matching this origin exist in (including this one) */ + spacesWithMatchingOrigins?: string[]; +} + +/** + * The response when object references are collected. + * + * @public + */ +export interface SavedObjectsCollectMultiNamespaceReferencesResponse { + objects: SavedObjectReferenceWithContext[]; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/create.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/create.ts new file mode 100644 index 0000000000000..2172b75be4b46 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/create.ts @@ -0,0 +1,57 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { + SavedObjectsMigrationVersion, + SavedObjectReference, +} from '@kbn/core-saved-objects-common'; +import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from './base'; + +/** + * + * @public + */ +export interface SavedObjectsCreateOptions extends SavedObjectsBaseOptions { + /** (not recommended) Specify an id for the document */ + id?: string; + /** Overwrite existing documents (defaults to false) */ + overwrite?: boolean; + /** + * An opaque version number which changes on each successful write operation. + * Can be used in conjunction with `overwrite` for implementing optimistic concurrency control. + **/ + version?: string; + /** {@inheritDoc SavedObjectsMigrationVersion} */ + migrationVersion?: SavedObjectsMigrationVersion; + /** + * A semver value that is used when upgrading objects between Kibana versions. If undefined, this will be automatically set to the current + * Kibana version when the object is created. If this is set to a non-semver value, or it is set to a semver value greater than the + * current Kibana version, it will result in an error. + * + * @remarks + * Do not attempt to set this manually. It should only be used if you retrieved an existing object that had the `coreMigrationVersion` + * field set and you want to create it again. + */ + coreMigrationVersion?: string; + references?: SavedObjectReference[]; + /** The Elasticsearch Refresh setting for this operation */ + refresh?: MutatingOperationRefreshSetting; + /** Optional ID of the original saved object, if this object's `id` was regenerated */ + originId?: string; + /** + * Optional initial namespaces for the object to be created in. If this is defined, it will supersede the namespace ID that is in + * {@link SavedObjectsCreateOptions}. + * + * * For shareable object types (registered with `namespaceType: 'multiple'`): this option can be used to specify one or more spaces, + * including the "All spaces" identifier (`'*'`). + * * For isolated object types (registered with `namespaceType: 'single'` or `namespaceType: 'multiple-isolated'`): this option can only + * be used to specify a single space, and the "All spaces" identifier (`'*'`) is not allowed. + * * For global object types (registered with `namespaceType: 'agnostic'`): this option cannot be used. + */ + initialNamespaces?: string[]; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/create_point_in_time_finder.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/create_point_in_time_finder.ts new file mode 100644 index 0000000000000..ea7e1f319a582 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/create_point_in_time_finder.ts @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectsFindOptions, SavedObjectsFindResponse } from './find'; +import type { SavedObjectsClientContract } from '../saved_objects_client'; + +/** + * @public + */ +export type SavedObjectsCreatePointInTimeFinderOptions = Omit< + SavedObjectsFindOptions, + 'page' | 'pit' | 'searchAfter' +>; + +/** + * @public + */ +export interface SavedObjectsCreatePointInTimeFinderDependencies { + client: Pick; +} + +/** @public */ +export interface ISavedObjectsPointInTimeFinder { + /** + * An async generator which wraps calls to `savedObjectsClient.find` and + * iterates over multiple pages of results using `_pit` and `search_after`. + * This will open a new Point-In-Time (PIT), and continue paging until a set + * of results is received that's smaller than the designated `perPage` size. + */ + find: () => AsyncGenerator>; + /** + * Closes the Point-In-Time associated with this finder instance. + * + * Once you have retrieved all of the results you need, it is recommended + * to call `close()` to clean up the PIT and prevent Elasticsearch from + * consuming resources unnecessarily. This is only required if you are + * done iterating and have not yet paged through all of the results: the + * PIT will automatically be closed for you once you reach the last page + * of results, or if the underlying call to `find` fails for any reason. + */ + close: () => Promise; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/delete.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/delete.ts new file mode 100644 index 0000000000000..36c5dab7d689e --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/delete.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from './base'; + +/** + * + * @public + */ +export interface SavedObjectsDeleteOptions extends SavedObjectsBaseOptions { + /** The Elasticsearch Refresh setting for this operation */ + refresh?: MutatingOperationRefreshSetting; + /** Force deletion of an object that exists in multiple namespaces */ + force?: boolean; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/delete_by_namespace.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/delete_by_namespace.ts new file mode 100644 index 0000000000000..17eda87e3dd70 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/delete_by_namespace.ts @@ -0,0 +1,18 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectsBaseOptions } from './base'; + +/** + * + * @public + */ +export interface SavedObjectsDeleteByNamespaceOptions extends SavedObjectsBaseOptions { + /** The Elasticsearch supports only boolean flag for this operation */ + refresh?: boolean; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/find.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/find.ts new file mode 100644 index 0000000000000..49042029f334b --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/find.ts @@ -0,0 +1,173 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { + SortOrder, + AggregationsAggregationContainer, + Id as EsId, +} from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; + +type KueryNode = any; + +/** + * @public + */ +export interface SavedObjectsFindOptionsReference { + type: string; + id: string; +} + +/** + * @public + */ +export interface SavedObjectsPitParams { + id: string; + keepAlive?: string; +} + +/** + * + * @public + */ +export interface SavedObjectsFindOptions { + type: string | string[]; + page?: number; + perPage?: number; + sortField?: string; + sortOrder?: SortOrder; + /** + * An array of fields to include in the results + * @example + * SavedObjects.find({type: 'dashboard', fields: ['attributes.name', 'attributes.location']}) + */ + fields?: string[]; + /** Search documents using the Elasticsearch Simple Query String syntax. See Elasticsearch Simple Query String `query` argument for more information */ + search?: string; + /** The fields to perform the parsed query against. See Elasticsearch Simple Query String `fields` argument for more information */ + searchFields?: string[]; + /** + * Use the sort values from the previous page to retrieve the next page of results. + */ + searchAfter?: EsId[]; + /** + * The fields to perform the parsed query against. Unlike the `searchFields` argument, these are expected to be root fields and will not + * be modified. If used in conjunction with `searchFields`, both are concatenated together. + */ + rootSearchFields?: string[]; + + /** + * Search for documents having a reference to the specified objects. + * Use `hasReferenceOperator` to specify the operator to use when searching for multiple references. + */ + hasReference?: SavedObjectsFindOptionsReference | SavedObjectsFindOptionsReference[]; + /** + * The operator to use when searching by multiple references using the `hasReference` option. Defaults to `OR` + */ + hasReferenceOperator?: 'AND' | 'OR'; + + /** + * The search operator to use with the provided filter. Defaults to `OR` + */ + defaultSearchOperator?: 'AND' | 'OR'; + filter?: string | KueryNode; + /** + * A record of aggregations to perform. + * The API currently only supports a limited set of metrics and bucket aggregation types. + * Additional aggregation types can be contributed to Core. + * + * @example + * Aggregating on SO attribute field + * ```ts + * const aggs = { latest_version: { max: { field: 'dashboard.attributes.version' } } }; + * return client.find({ type: 'dashboard', aggs }) + * ``` + * + * @example + * Aggregating on SO root field + * ```ts + * const aggs = { latest_update: { max: { field: 'dashboard.updated_at' } } }; + * return client.find({ type: 'dashboard', aggs }) + * ``` + * + * @alpha + */ + aggs?: Record; + namespaces?: string[]; + /** + * This map defines each type to search for, and the namespace(s) to search for the type in; this is only intended to be used by a saved + * object client wrapper. + * If this is defined, it supersedes the `type` and `namespaces` fields when building the Elasticsearch query. + * Any types that are not included in this map will be excluded entirely. + * If a type is included but its value is undefined, the operation will search for that type in the Default namespace. + */ + typeToNamespacesMap?: Map; + /** An optional ES preference value to be used for the query **/ + preference?: string; + /** + * Search against a specific Point In Time (PIT) that you've opened with {@link SavedObjectsClient.openPointInTimeForType}. + */ + pit?: SavedObjectsPitParams; +} + +/** + * + * @public + */ +export interface SavedObjectsFindResult extends SavedObject { + /** + * The Elasticsearch `_score` of this result. + */ + score: number; + /** + * The Elasticsearch `sort` value of this result. + * + * @remarks + * This can be passed directly to the `searchAfter` param in the {@link SavedObjectsFindOptions} + * in order to page through large numbers of hits. It is recommended you use this alongside + * a Point In Time (PIT) that was opened with {@link SavedObjectsClient.openPointInTimeForType}. + * + * @example + * ```ts + * const { id } = await savedObjectsClient.openPointInTimeForType('visualization'); + * const page1 = await savedObjectsClient.find({ + * type: 'visualization', + * sortField: 'updated_at', + * sortOrder: 'asc', + * pit: { id }, + * }); + * const lastHit = page1.saved_objects[page1.saved_objects.length - 1]; + * const page2 = await savedObjectsClient.find({ + * type: 'visualization', + * sortField: 'updated_at', + * sortOrder: 'asc', + * pit: { id: page1.pit_id }, + * searchAfter: lastHit.sort, + * }); + * await savedObjectsClient.closePointInTime(page2.pit_id); + * ``` + */ + sort?: string[]; +} + +/** + * Return type of the Saved Objects `find()` method. + * + * *Note*: this type is different between the Public and Server Saved Objects + * clients. + * + * @public + */ +export interface SavedObjectsFindResponse { + aggregations?: A; + saved_objects: Array>; + total: number; + per_page: number; + page: number; + pit_id?: string; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/increment_counter.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/increment_counter.ts new file mode 100644 index 0000000000000..8a87bb7b38b06 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/increment_counter.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectsMigrationVersion } from '@kbn/core-saved-objects-common'; +import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from './base'; + +/** + * @public + */ +export interface SavedObjectsIncrementCounterOptions + extends SavedObjectsBaseOptions { + /** + * (default=false) If true, sets all the counter fields to 0 if they don't + * already exist. Existing fields will be left as-is and won't be incremented. + */ + initialize?: boolean; + /** {@link SavedObjectsMigrationVersion} */ + migrationVersion?: SavedObjectsMigrationVersion; + /** + * (default='wait_for') The Elasticsearch refresh setting for this + * operation. See {@link MutatingOperationRefreshSetting} + */ + refresh?: MutatingOperationRefreshSetting; + /** + * Attributes to use when upserting the document if it doesn't exist. + */ + upsertAttributes?: Attributes; +} + +/** + * @public + */ +export interface SavedObjectsIncrementCounterField { + /** The field name to increment the counter by.*/ + fieldName: string; + /** The number to increment the field by (defaults to 1).*/ + incrementBy?: number; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/index.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/index.ts new file mode 100644 index 0000000000000..53457c98f20f6 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/index.ts @@ -0,0 +1,73 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export type { + SavedObjectsBaseOptions, + MutatingOperationRefreshSetting, + SavedObjectsBulkResponse, +} from './base'; +export type { SavedObjectsBulkCreateObject } from './bulk_create'; +export type { SavedObjectsBulkGetObject } from './bulk_get'; +export type { + SavedObjectsBulkResolveObject, + SavedObjectsBulkResolveResponse, +} from './bulk_resolve'; +export type { + SavedObjectsBulkUpdateObject, + SavedObjectsBulkUpdateResponse, + SavedObjectsBulkUpdateOptions, +} from './bulk_update'; +export type { + SavedObjectsCheckConflictsObject, + SavedObjectsCheckConflictsResponse, +} from './check_conflicts'; +export type { + SavedObjectsClosePointInTimeOptions, + SavedObjectsClosePointInTimeResponse, +} from './close_point_in_time'; +export type { + SavedObjectsCollectMultiNamespaceReferencesObject, + SavedObjectReferenceWithContext, + SavedObjectsCollectMultiNamespaceReferencesResponse, + SavedObjectsCollectMultiNamespaceReferencesOptions, +} from './collect_multinamespace_references'; +export type { SavedObjectsCreateOptions } from './create'; +export type { + SavedObjectsCreatePointInTimeFinderOptions, + SavedObjectsCreatePointInTimeFinderDependencies, + ISavedObjectsPointInTimeFinder, +} from './create_point_in_time_finder'; +export type { SavedObjectsDeleteOptions } from './delete'; +export type { SavedObjectsDeleteByNamespaceOptions } from './delete_by_namespace'; +export type { + SavedObjectsFindOptions, + SavedObjectsFindOptionsReference, + SavedObjectsFindResponse, + SavedObjectsFindResult, + SavedObjectsPitParams, +} from './find'; +export type { + SavedObjectsIncrementCounterField, + SavedObjectsIncrementCounterOptions, +} from './increment_counter'; +export type { + SavedObjectsOpenPointInTimeOptions, + SavedObjectsOpenPointInTimeResponse, +} from './open_point_in_time_for_type'; +export type { + SavedObjectsRemoveReferencesToOptions, + SavedObjectsRemoveReferencesToResponse, +} from './remove_references_to'; +export type { SavedObjectsResolveResponse } from './resolve'; +export type { SavedObjectsUpdateResponse, SavedObjectsUpdateOptions } from './update'; +export type { + SavedObjectsUpdateObjectsSpacesObject, + SavedObjectsUpdateObjectsSpacesResponse, + SavedObjectsUpdateObjectsSpacesOptions, + SavedObjectsUpdateObjectsSpacesResponseObject, +} from './update_objects_spaces'; diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/open_point_in_time_for_type.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/open_point_in_time_for_type.ts new file mode 100644 index 0000000000000..ad9a2face8b06 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/open_point_in_time_for_type.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +/** + * @public + */ +export interface SavedObjectsOpenPointInTimeOptions { + /** + * Optionally specify how long ES should keep the PIT alive until the next request. Defaults to `5m`. + */ + keepAlive?: string; + /** + * An optional ES preference value to be used for the query. + */ + preference?: string; + /** + * An optional list of namespaces to be used when opening the PIT. + * + * When the spaces plugin is enabled: + * - this will default to the user's current space (as determined by the URL) + * - if specified, the user's current space will be ignored + * - `['*']` will search across all available spaces + */ + namespaces?: string[]; +} + +/** + * @public + */ +export interface SavedObjectsOpenPointInTimeResponse { + /** + * PIT ID returned from ES. + */ + id: string; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/remove_references_to.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/remove_references_to.ts new file mode 100644 index 0000000000000..4e5be5fda67f2 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/remove_references_to.ts @@ -0,0 +1,27 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectsBaseOptions } from './base'; + +/** + * + * @public + */ +export interface SavedObjectsRemoveReferencesToOptions extends SavedObjectsBaseOptions { + /** The Elasticsearch Refresh setting for this operation. Defaults to `true` */ + refresh?: boolean; +} + +/** + * + * @public + */ +export interface SavedObjectsRemoveReferencesToResponse extends SavedObjectsBaseOptions { + /** The number of objects that have been updated by this operation */ + updated: number; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/resolve.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/resolve.ts new file mode 100644 index 0000000000000..9e764053392a5 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/resolve.ts @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObject } from '@kbn/core-saved-objects-common'; + +/** + * + * @public + */ +export interface SavedObjectsResolveResponse { + /** + * The saved object that was found. + */ + saved_object: SavedObject; + /** + * The outcome for a successful `resolve` call is one of the following values: + * + * * `'exactMatch'` -- One document exactly matched the given ID. + * * `'aliasMatch'` -- One document with a legacy URL alias matched the given ID; in this case the `saved_object.id` field is different + * than the given ID. + * * `'conflict'` -- Two documents matched the given ID, one was an exact match and another with a legacy URL alias; in this case the + * `saved_object` object is the exact match, and the `saved_object.id` field is the same as the given ID. + */ + outcome: 'exactMatch' | 'aliasMatch' | 'conflict'; + /** + * The ID of the object that the legacy URL alias points to. + * + * **Note:** this field is *only* included when an alias was found (in other words, when the outcome is `'aliasMatch'` or `'conflict'`). + */ + alias_target_id?: string; + /** + * The reason this alias was created. + * + * Currently this is used to determine whether or not a toast should be shown when a user is redirected from a legacy URL; if the alias + * was created because of saved object conversion, then we will display a toast telling the user that the object has a new URL. + * + * **Note:** this field is *only* included when an alias was found (in other words, when the outcome is `'aliasMatch'` or `'conflict'`). + */ + alias_purpose?: 'savedObjectConversion' | 'savedObjectImport'; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/update.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/update.ts new file mode 100644 index 0000000000000..31bac37b94fff --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/update.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectReference, SavedObject } from '@kbn/core-saved-objects-common'; +import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from './base'; + +/** + * + * @public + */ +export interface SavedObjectsUpdateOptions extends SavedObjectsBaseOptions { + /** + * An opaque version number which changes on each successful write operation. + * Can be used for implementing optimistic concurrency control. + */ + version?: string; + /** {@inheritdoc SavedObjectReference} */ + references?: SavedObjectReference[]; + /** The Elasticsearch Refresh setting for this operation */ + refresh?: MutatingOperationRefreshSetting; + /** If specified, will be used to perform an upsert if the document doesn't exist */ + upsert?: Attributes; + /** + * The Elasticsearch `retry_on_conflict` setting for this operation. + * Defaults to `0` when `version` is provided, `3` otherwise. + */ + retryOnConflict?: number; +} + +/** + * + * @public + */ +export interface SavedObjectsUpdateResponse + extends Omit, 'attributes' | 'references'> { + attributes: Partial; + references: SavedObjectReference[] | undefined; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/apis/update_objects_spaces.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/update_objects_spaces.ts new file mode 100644 index 0000000000000..148d3480f2975 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/apis/update_objects_spaces.ts @@ -0,0 +1,69 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectError } from '@kbn/core-saved-objects-common'; +import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from './base'; + +/** + * An object that should have its spaces updated. + * + * @public + */ +export interface SavedObjectsUpdateObjectsSpacesObject { + /** The type of the object to update */ + id: string; + /** The ID of the object to update */ + type: string; + /** + * The space(s) that the object to update currently exists in. This is only intended to be used by SOC wrappers. + * + * @internal + */ + spaces?: string[]; + /** + * The version of the object to update; this is used for optimistic concurrency control. This is only intended to be used by SOC wrappers. + * + * @internal + */ + version?: string; +} + +/** + * Options for the update operation. + * + * @public + */ +export interface SavedObjectsUpdateObjectsSpacesOptions extends SavedObjectsBaseOptions { + /** The Elasticsearch Refresh setting for this operation */ + refresh?: MutatingOperationRefreshSetting; +} + +/** + * The response when objects' spaces are updated. + * + * @public + */ +export interface SavedObjectsUpdateObjectsSpacesResponse { + objects: SavedObjectsUpdateObjectsSpacesResponseObject[]; +} + +/** + * Details about a specific object's update result. + * + * @public + */ +export interface SavedObjectsUpdateObjectsSpacesResponseObject { + /** The type of the referenced object */ + type: string; + /** The ID of the referenced object */ + id: string; + /** The space(s) that the referenced object exists in */ + spaces: string[]; + /** Included if there was an error updating this object's spaces */ + error?: SavedObjectError; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/index.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/index.ts new file mode 100644 index 0000000000000..f10ee8e548819 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/index.ts @@ -0,0 +1,54 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export type { SavedObjectsClientContract } from './saved_objects_client'; +export type { ISavedObjectsRepository } from './saved_objects_repository'; +export type { + MutatingOperationRefreshSetting, + SavedObjectsBaseOptions, + SavedObjectsIncrementCounterOptions, + SavedObjectsDeleteByNamespaceOptions, + SavedObjectsBulkResponse, + SavedObjectsUpdateResponse, + SavedObjectsBulkGetObject, + SavedObjectsBulkResolveObject, + SavedObjectsIncrementCounterField, + SavedObjectsBulkCreateObject, + SavedObjectsBulkResolveResponse, + SavedObjectsCreateOptions, + SavedObjectsFindResponse, + SavedObjectsBulkUpdateResponse, + SavedObjectsUpdateObjectsSpacesResponse, + SavedObjectsUpdateObjectsSpacesOptions, + SavedObjectsCollectMultiNamespaceReferencesOptions, + SavedObjectsCollectMultiNamespaceReferencesResponse, + SavedObjectsRemoveReferencesToResponse, + SavedObjectsCheckConflictsObject, + SavedObjectsCheckConflictsResponse, + SavedObjectsBulkUpdateOptions, + SavedObjectsFindOptionsReference, + SavedObjectsFindResult, + SavedObjectsRemoveReferencesToOptions, + SavedObjectsDeleteOptions, + SavedObjectsOpenPointInTimeResponse, + SavedObjectsBulkUpdateObject, + SavedObjectsClosePointInTimeResponse, + ISavedObjectsPointInTimeFinder, + SavedObjectsCreatePointInTimeFinderDependencies, + SavedObjectsPitParams, + SavedObjectsResolveResponse, + SavedObjectsCollectMultiNamespaceReferencesObject, + SavedObjectsUpdateObjectsSpacesResponseObject, + SavedObjectsUpdateObjectsSpacesObject, + SavedObjectReferenceWithContext, + SavedObjectsUpdateOptions, + SavedObjectsOpenPointInTimeOptions, + SavedObjectsClosePointInTimeOptions, + SavedObjectsCreatePointInTimeFinderOptions, + SavedObjectsFindOptions, +} from './apis'; diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/saved_objects_client.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/saved_objects_client.ts new file mode 100644 index 0000000000000..82808e4024c73 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/saved_objects_client.ts @@ -0,0 +1,359 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObject } from '@kbn/core-saved-objects-common'; +import type { + SavedObjectsBaseOptions, + SavedObjectsFindOptions, + SavedObjectsClosePointInTimeOptions, + SavedObjectsOpenPointInTimeOptions, + SavedObjectsCreatePointInTimeFinderOptions, + SavedObjectsUpdateOptions, + SavedObjectsUpdateResponse, + SavedObjectsUpdateObjectsSpacesObject, + SavedObjectsUpdateObjectsSpacesOptions, + SavedObjectsCollectMultiNamespaceReferencesObject, + SavedObjectsUpdateObjectsSpacesResponse, + SavedObjectsResolveResponse, + ISavedObjectsPointInTimeFinder, + SavedObjectsRemoveReferencesToOptions, + SavedObjectsClosePointInTimeResponse, + SavedObjectsDeleteOptions, + SavedObjectsCreatePointInTimeFinderDependencies, + SavedObjectsCheckConflictsResponse, + SavedObjectsBulkUpdateOptions, + SavedObjectsCollectMultiNamespaceReferencesResponse, + SavedObjectsBulkUpdateResponse, + SavedObjectsFindResponse, + SavedObjectsCreateOptions, + SavedObjectsCheckConflictsObject, + SavedObjectsBulkUpdateObject, + SavedObjectsBulkResolveResponse, + SavedObjectsBulkResolveObject, + SavedObjectsBulkGetObject, + SavedObjectsBulkCreateObject, + SavedObjectsOpenPointInTimeResponse, + SavedObjectsRemoveReferencesToResponse, + SavedObjectsCollectMultiNamespaceReferencesOptions, + SavedObjectsBulkResponse, +} from './apis'; + +/** + * Saved Objects is Kibana's data persisentence mechanism allowing plugins to + * use Elasticsearch for storing plugin state. + * + * ## SavedObjectsClient errors + * + * Since the SavedObjectsClient has its hands in everything we + * are a little paranoid about the way we present errors back to + * to application code. Ideally, all errors will be either: + * + * 1. Caused by bad implementation (ie. undefined is not a function) and + * as such unpredictable + * 2. An error that has been classified and decorated appropriately + * by the decorators in {@link SavedObjectsErrorHelpers} + * + * Type 1 errors are inevitable, but since all expected/handle-able errors + * should be Type 2 the `isXYZError()` helpers exposed at + * `SavedObjectsErrorHelpers` should be used to understand and manage error + * responses from the `SavedObjectsClient`. + * + * Type 2 errors are decorated versions of the source error, so if + * the elasticsearch client threw an error it will be decorated based + * on its type. That means that rather than looking for `error.body.error.type` or + * doing substring checks on `error.body.error.reason`, just use the helpers to + * understand the meaning of the error: + * + * ```js + * if (SavedObjectsErrorHelpers.isNotFoundError(error)) { + * // handle 404 + * } + * + * if (SavedObjectsErrorHelpers.isNotAuthorizedError(error)) { + * // 401 handling should be automatic, but in case you wanted to know + * } + * + * // always rethrow the error unless you handle it + * throw error; + * ``` + * + * ### 404s from missing index + * + * From the perspective of application code and APIs the SavedObjectsClient is + * a black box that persists objects. One of the internal details that users have + * no control over is that we use an elasticsearch index for persistence and that + * index might be missing. + * + * At the time of writing we are in the process of transitioning away from the + * operating assumption that the SavedObjects index is always available. Part of + * this transition is handling errors resulting from an index missing. These used + * to trigger a 500 error in most cases, and in others cause 404s with different + * error messages. + * + * From my (Spencer) perspective, a 404 from the SavedObjectsApi is a 404; The + * object the request/call was targeting could not be found. This is why #14141 + * takes special care to ensure that 404 errors are generic and don't distinguish + * between index missing or document missing. + * + * See {@link SavedObjectsClient} + * See {@link SavedObjectsErrorHelpers} + * + * @public + */ +export interface SavedObjectsClientContract { + /** + * Persists a SavedObject + * + * @param type + * @param attributes + * @param options + */ + create( + type: string, + attributes: T, + options?: SavedObjectsCreateOptions + ): Promise>; + + /** + * Persists multiple documents batched together as a single request + * + * @param objects + * @param options + */ + bulkCreate( + objects: Array>, + options?: SavedObjectsCreateOptions + ): Promise>; + + /** + * Check what conflicts will result when creating a given array of saved objects. This includes "unresolvable conflicts", which are + * multi-namespace objects that exist in a different namespace; such conflicts cannot be resolved/overwritten. + * + * @param objects + * @param options + */ + checkConflicts( + objects: SavedObjectsCheckConflictsObject[], + options?: SavedObjectsBaseOptions + ): Promise; + + /** + * Deletes a SavedObject + * + * @param type + * @param id + * @param options + */ + delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>; + + /** + * Find all SavedObjects matching the search query + * + * @param options + */ + find( + options: SavedObjectsFindOptions + ): Promise>; + + /** + * Returns an array of objects by id + * + * @param objects - an array of ids, or an array of objects containing id, type and optionally fields + * @example + * + * bulkGet([ + * { id: 'one', type: 'config' }, + * { id: 'foo', type: 'index-pattern' } + * ]) + */ + bulkGet( + objects: SavedObjectsBulkGetObject[], + options?: SavedObjectsBaseOptions + ): Promise>; + + /** + * Retrieves a single object + * + * @param type - The type of SavedObject to retrieve + * @param id - The ID of the SavedObject to retrieve + * @param options + */ + get( + type: string, + id: string, + options?: SavedObjectsBaseOptions + ): Promise>; + + /** + * Resolves an array of objects by id, using any legacy URL aliases if they exist + * + * @param objects - an array of objects containing id, type + * @example + * + * bulkResolve([ + * { id: 'one', type: 'config' }, + * { id: 'foo', type: 'index-pattern' } + * ]) + * + * @note Saved objects that Kibana fails to find are replaced with an error object and an "exactMatch" outcome. The rationale behind the + * outcome is that "exactMatch" is the default outcome, and the outcome only changes if an alias is found. This behavior is unique to + * `bulkResolve`; the regular `resolve` API will throw an error instead. + */ + bulkResolve( + objects: SavedObjectsBulkResolveObject[], + options?: SavedObjectsBaseOptions + ): Promise>; + + /** + * Resolves a single object, using any legacy URL alias if it exists + * + * @param type - The type of SavedObject to retrieve + * @param id - The ID of the SavedObject to retrieve + * @param options + */ + resolve( + type: string, + id: string, + options?: SavedObjectsBaseOptions + ): Promise>; + + /** + * Updates an SavedObject + * + * @param type + * @param id + * @param options + */ + update( + type: string, + id: string, + attributes: Partial, + options?: SavedObjectsUpdateOptions + ): Promise>; + + /** + * Bulk Updates multiple SavedObject at once + * + * @param objects + */ + bulkUpdate( + objects: Array>, + options?: SavedObjectsBulkUpdateOptions + ): Promise>; + + /** + * Updates all objects containing a reference to the given {type, id} tuple to remove the said reference. + */ + removeReferencesTo( + type: string, + id: string, + options?: SavedObjectsRemoveReferencesToOptions + ): Promise; + + /** + * Opens a Point In Time (PIT) against the indices for the specified Saved Object types. + * The returned `id` can then be passed to {@link SavedObjectsClient.find} to search + * against that PIT. + * + * Only use this API if you have an advanced use case that's not solved by the + * {@link SavedObjectsClient.createPointInTimeFinder} method. + */ + openPointInTimeForType( + type: string | string[], + options?: SavedObjectsOpenPointInTimeOptions + ): Promise; + + /** + * Closes a Point In Time (PIT) by ID. This simply proxies the request to ES via the + * Elasticsearch client, and is included in the Saved Objects Client as a convenience + * for consumers who are using {@link SavedObjectsClient.openPointInTimeForType}. + * + * Only use this API if you have an advanced use case that's not solved by the + * {@link SavedObjectsClient.createPointInTimeFinder} method. + */ + closePointInTime( + id: string, + options?: SavedObjectsClosePointInTimeOptions + ): Promise; + + /** + * Returns a {@link ISavedObjectsPointInTimeFinder} to help page through + * large sets of saved objects. We strongly recommend using this API for + * any `find` queries that might return more than 1000 saved objects, + * however this API is only intended for use in server-side "batch" + * processing of objects where you are collecting all objects in memory + * or streaming them back to the client. + * + * Do NOT use this API in a route handler to facilitate paging through + * saved objects on the client-side unless you are streaming all of the + * results back to the client at once. Because the returned generator is + * stateful, you cannot rely on subsequent http requests retrieving new + * pages from the same Kibana server in multi-instance deployments. + * + * The generator wraps calls to {@link SavedObjectsClient.find} and iterates + * over multiple pages of results using `_pit` and `search_after`. This will + * open a new Point-In-Time (PIT), and continue paging until a set of + * results is received that's smaller than the designated `perPage`. + * + * Once you have retrieved all of the results you need, it is recommended + * to call `close()` to clean up the PIT and prevent Elasticsearch from + * consuming resources unnecessarily. This is only required if you are + * done iterating and have not yet paged through all of the results: the + * PIT will automatically be closed for you once you reach the last page + * of results, or if the underlying call to `find` fails for any reason. + * + * @example + * ```ts + * const findOptions: SavedObjectsCreatePointInTimeFinderOptions = { + * type: 'visualization', + * search: 'foo*', + * perPage: 100, + * }; + * + * const finder = savedObjectsClient.createPointInTimeFinder(findOptions); + * + * const responses: SavedObjectFindResponse[] = []; + * for await (const response of finder.find()) { + * responses.push(...response); + * if (doneSearching) { + * await finder.close(); + * } + * } + * ``` + */ + createPointInTimeFinder( + findOptions: SavedObjectsCreatePointInTimeFinderOptions, + dependencies?: SavedObjectsCreatePointInTimeFinderDependencies + ): ISavedObjectsPointInTimeFinder; + + /** + * Gets all references and transitive references of the listed objects. Ignores any object that is not a multi-namespace type. + * + * @param objects + * @param options + */ + collectMultiNamespaceReferences( + objects: SavedObjectsCollectMultiNamespaceReferencesObject[], + options?: SavedObjectsCollectMultiNamespaceReferencesOptions + ): Promise; + + /** + * Updates one or more objects to add and/or remove them from specified spaces. + * + * @param objects + * @param spacesToAdd + * @param spacesToRemove + * @param options + */ + updateObjectsSpaces( + objects: SavedObjectsUpdateObjectsSpacesObject[], + spacesToAdd: string[], + spacesToRemove: string[], + options?: SavedObjectsUpdateObjectsSpacesOptions + ): Promise; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/src/saved_objects_repository.ts b/packages/core/saved-objects/core-saved-objects-api-server/src/saved_objects_repository.ts new file mode 100644 index 0000000000000..102afce9dd73d --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/src/saved_objects_repository.ts @@ -0,0 +1,476 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObject } from '@kbn/core-saved-objects-common'; +import type { + SavedObjectsBaseOptions, + SavedObjectsFindOptions, + SavedObjectsClosePointInTimeOptions, + SavedObjectsOpenPointInTimeOptions, + SavedObjectsCreatePointInTimeFinderOptions, + SavedObjectsUpdateOptions, + SavedObjectsUpdateResponse, + SavedObjectsUpdateObjectsSpacesObject, + SavedObjectsUpdateObjectsSpacesOptions, + SavedObjectsCollectMultiNamespaceReferencesObject, + SavedObjectsUpdateObjectsSpacesResponse, + SavedObjectsResolveResponse, + ISavedObjectsPointInTimeFinder, + SavedObjectsRemoveReferencesToOptions, + SavedObjectsClosePointInTimeResponse, + SavedObjectsDeleteOptions, + SavedObjectsCreatePointInTimeFinderDependencies, + SavedObjectsCheckConflictsResponse, + SavedObjectsBulkUpdateOptions, + SavedObjectsCollectMultiNamespaceReferencesResponse, + SavedObjectsBulkUpdateResponse, + SavedObjectsFindResponse, + SavedObjectsCreateOptions, + SavedObjectsCheckConflictsObject, + SavedObjectsBulkUpdateObject, + SavedObjectsBulkResolveResponse, + SavedObjectsBulkResolveObject, + SavedObjectsBulkGetObject, + SavedObjectsBulkCreateObject, + SavedObjectsOpenPointInTimeResponse, + SavedObjectsRemoveReferencesToResponse, + SavedObjectsCollectMultiNamespaceReferencesOptions, + SavedObjectsBulkResponse, + SavedObjectsDeleteByNamespaceOptions, + SavedObjectsIncrementCounterField, + SavedObjectsIncrementCounterOptions, +} from './apis'; + +/** + * The savedObjects repository contract. + * + * @public + */ +export interface ISavedObjectsRepository { + /** + * Persists an object + * + * @param {string} type + * @param {object} attributes + * @param {object} [options={}] + * @property {string} [options.id] - force id on creation, not recommended + * @property {boolean} [options.overwrite=false] + * @property {object} [options.migrationVersion=undefined] + * @property {string} [options.namespace] + * @property {array} [options.references=[]] - [{ name, type, id }] + * @returns {promise} - { id, type, version, attributes } + */ + create( + type: string, + attributes: T, + options?: SavedObjectsCreateOptions + ): Promise>; + + /** + * Creates multiple documents at once + * + * @param {array} objects - [{ type, id, attributes, references, migrationVersion }] + * @param {object} [options={}] + * @property {boolean} [options.overwrite=false] - overwrites existing documents + * @property {string} [options.namespace] + * @returns {promise} - {saved_objects: [[{ id, type, version, references, attributes, error: { message } }]} + */ + bulkCreate( + objects: Array>, + options?: SavedObjectsCreateOptions + ): Promise>; + + /** + * Check what conflicts will result when creating a given array of saved objects. This includes "unresolvable conflicts", which are + * multi-namespace objects that exist in a different namespace; such conflicts cannot be resolved/overwritten. + */ + checkConflicts( + objects: SavedObjectsCheckConflictsObject[], + options?: SavedObjectsBaseOptions + ): Promise; + + /** + * Deletes an object + * + * @param {string} type + * @param {string} id + * @param {object} [options={}] + * @property {string} [options.namespace] + * @returns {promise} + */ + delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>; + + /** + * Deletes all objects from the provided namespace. + * + * @param {string} namespace + * @returns {promise} - { took, timed_out, total, deleted, batches, version_conflicts, noops, retries, failures } + */ + deleteByNamespace( + namespace: string, + options?: SavedObjectsDeleteByNamespaceOptions + ): Promise; + + /** + * @param {object} [options={}] + * @property {(string|Array)} [options.type] + * @property {string} [options.search] + * @property {string} [options.defaultSearchOperator] + * @property {Array} [options.searchFields] - see Elasticsearch Simple Query String + * Query field argument for more information + * @property {integer} [options.page=1] + * @property {integer} [options.perPage=20] + * @property {Array} [options.searchAfter] + * @property {string} [options.sortField] + * @property {string} [options.sortOrder] + * @property {Array} [options.fields] + * @property {string} [options.namespace] + * @property {object} [options.hasReference] - { type, id } + * @property {string} [options.pit] + * @property {string} [options.preference] + * @returns {promise} - { saved_objects: [{ id, type, version, attributes }], total, per_page, page } + */ + find( + options: SavedObjectsFindOptions + ): Promise>; + + /** + * Returns an array of objects by id + * + * @param {array} objects - an array of objects containing id, type and optionally fields + * @param {object} [options={}] + * @property {string} [options.namespace] + * @returns {promise} - { saved_objects: [{ id, type, version, attributes }] } + * @example + * + * bulkGet([ + * { id: 'one', type: 'config' }, + * { id: 'foo', type: 'index-pattern' } + * ]) + */ + bulkGet( + objects: SavedObjectsBulkGetObject[], + options?: SavedObjectsBaseOptions + ): Promise>; + + /** + * Resolves an array of objects by id, using any legacy URL aliases if they exist + * + * @param {array} objects - an array of objects containing id, type + * @param {object} [options={}] + * @property {string} [options.namespace] + * @returns {promise} - { resolved_objects: [{ saved_object, outcome }] } + * @example + * + * bulkResolve([ + * { id: 'one', type: 'config' }, + * { id: 'foo', type: 'index-pattern' } + * ]) + */ + bulkResolve( + objects: SavedObjectsBulkResolveObject[], + options?: SavedObjectsBaseOptions + ): Promise>; + + /** + * Gets a single object + * + * @param {string} type + * @param {string} id + * @param {object} [options={}] + * @property {string} [options.namespace] + * @returns {promise} - { id, type, version, attributes } + */ + get( + type: string, + id: string, + options?: SavedObjectsBaseOptions + ): Promise>; + + /** + * Resolves a single object, using any legacy URL alias if it exists + * + * @param {string} type + * @param {string} id + * @param {object} [options={}] + * @property {string} [options.namespace] + * @returns {promise} - { saved_object, outcome } + */ + resolve( + type: string, + id: string, + options?: SavedObjectsBaseOptions + ): Promise>; + + /** + * Updates an object + * + * @param {string} type + * @param {string} id + * @param {object} [options={}] + * @property {string} options.version - ensures version matches that of persisted object + * @property {string} [options.namespace] + * @property {array} [options.references] - [{ name, type, id }] + * @returns {promise} + */ + update( + type: string, + id: string, + attributes: Partial, + options?: SavedObjectsUpdateOptions + ): Promise>; + + /** + * Gets all references and transitive references of the given objects. Ignores any object and/or reference that is not a multi-namespace + * type. + * + * @param objects The objects to get the references for. + */ + collectMultiNamespaceReferences( + objects: SavedObjectsCollectMultiNamespaceReferencesObject[], + options?: SavedObjectsCollectMultiNamespaceReferencesOptions + ): Promise; + + /** + * Updates one or more objects to add and/or remove them from specified spaces. + * + * @param objects + * @param spacesToAdd + * @param spacesToRemove + * @param options + */ + updateObjectsSpaces( + objects: SavedObjectsUpdateObjectsSpacesObject[], + spacesToAdd: string[], + spacesToRemove: string[], + options?: SavedObjectsUpdateObjectsSpacesOptions + ): Promise; + + /** + * Updates multiple objects in bulk + * + * @param {array} objects - [{ type, id, attributes, options: { version, namespace } references }] + * @property {string} options.version - ensures version matches that of persisted object + * @property {string} [options.namespace] + * @returns {promise} - {saved_objects: [[{ id, type, version, references, attributes, error: { message } }]} + */ + bulkUpdate( + objects: Array>, + options?: SavedObjectsBulkUpdateOptions + ): Promise>; + + /** + * Updates all objects containing a reference to the given {type, id} tuple to remove the said reference. + * + * @remarks Will throw a conflict error if the `update_by_query` operation returns any failure. In that case + * some references might have been removed, and some were not. It is the caller's responsibility + * to handle and fix this situation if it was to happen. + */ + removeReferencesTo( + type: string, + id: string, + options?: SavedObjectsRemoveReferencesToOptions + ): Promise; + + /** + * Increments all the specified counter fields (by one by default). Creates the document + * if one doesn't exist for the given id. + * + * @remarks + * When supplying a field name like `stats.api.counter` the field name will + * be used as-is to create a document like: + * `{attributes: {'stats.api.counter': 1}}` + * It will not create a nested structure like: + * `{attributes: {stats: {api: {counter: 1}}}}` + * + * When using incrementCounter for collecting usage data, you need to ensure + * that usage collection happens on a best-effort basis and doesn't + * negatively affect your plugin or users. See https://github.com/elastic/kibana/blob/main/src/plugins/usage_collection/README.mdx#tracking-interactions-with-incrementcounter) + * + * @example + * ```ts + * const repository = coreStart.savedObjects.createInternalRepository(); + * + * // Initialize all fields to 0 + * repository + * .incrementCounter('dashboard_counter_type', 'counter_id', [ + * 'stats.apiCalls', + * 'stats.sampleDataInstalled', + * ], {initialize: true}); + * + * // Increment the apiCalls field counter + * repository + * .incrementCounter('dashboard_counter_type', 'counter_id', [ + * 'stats.apiCalls', + * ]) + * + * // Increment the apiCalls field counter by 4 + * repository + * .incrementCounter('dashboard_counter_type', 'counter_id', [ + * { fieldName: 'stats.apiCalls' incrementBy: 4 }, + * ]) + * + * // Initialize the document with arbitrary fields if not present + * repository.incrementCounter<{ appId: string }>( + * 'dashboard_counter_type', + * 'counter_id', + * [ 'stats.apiCalls'], + * { upsertAttributes: { appId: 'myId' } } + * ) + * ``` + * + * @param type - The type of saved object whose fields should be incremented + * @param id - The id of the document whose fields should be incremented + * @param counterFields - An array of field names to increment or an array of {@link SavedObjectsIncrementCounterField} + * @param options - {@link SavedObjectsIncrementCounterOptions} + * @returns The saved object after the specified fields were incremented + */ + incrementCounter( + type: string, + id: string, + counterFields: Array, + options?: SavedObjectsIncrementCounterOptions + ): Promise>; + + /** + * Opens a Point In Time (PIT) against the indices for the specified Saved Object types. + * The returned `id` can then be passed to `SavedObjects.find` to search against that PIT. + * + * Only use this API if you have an advanced use case that's not solved by the + * {@link SavedObjectsRepository.createPointInTimeFinder} method. + * + * @example + * ```ts + * const { id } = await savedObjectsClient.openPointInTimeForType( + * type: 'visualization', + * { keepAlive: '5m' }, + * ); + * const page1 = await savedObjectsClient.find({ + * type: 'visualization', + * sortField: 'updated_at', + * sortOrder: 'asc', + * pit: { id, keepAlive: '2m' }, + * }); + * const lastHit = page1.saved_objects[page1.saved_objects.length - 1]; + * const page2 = await savedObjectsClient.find({ + * type: 'visualization', + * sortField: 'updated_at', + * sortOrder: 'asc', + * pit: { id: page1.pit_id }, + * searchAfter: lastHit.sort, + * }); + * await savedObjectsClient.closePointInTime(page2.pit_id); + * ``` + * + * @param {string|Array} type + * @param {object} [options] - {@link SavedObjectsOpenPointInTimeOptions} + * @property {string} [options.keepAlive] + * @property {string} [options.preference] + * @returns {promise} - { id: string } + */ + openPointInTimeForType( + type: string | string[], + options?: SavedObjectsOpenPointInTimeOptions + ): Promise; + + /** + * Closes a Point In Time (PIT) by ID. This simply proxies the request to ES + * via the Elasticsearch client, and is included in the Saved Objects Client + * as a convenience for consumers who are using `openPointInTimeForType`. + * + * Only use this API if you have an advanced use case that's not solved by the + * {@link SavedObjectsRepository.createPointInTimeFinder} method. + * + * @remarks + * While the `keepAlive` that is provided will cause a PIT to automatically close, + * it is highly recommended to explicitly close a PIT when you are done with it + * in order to avoid consuming unneeded resources in Elasticsearch. + * + * @example + * ```ts + * const repository = coreStart.savedObjects.createInternalRepository(); + * + * const { id } = await repository.openPointInTimeForType( + * type: 'index-pattern', + * { keepAlive: '2m' }, + * ); + * + * const response = await repository.find({ + * type: 'index-pattern', + * search: 'foo*', + * sortField: 'name', + * sortOrder: 'desc', + * pit: { + * id: 'abc123', + * keepAlive: '2m', + * }, + * searchAfter: [1234, 'abcd'], + * }); + * + * await repository.closePointInTime(response.pit_id); + * ``` + * + * @param {string} id + * @param {object} [options] - {@link SavedObjectsClosePointInTimeOptions} + * @returns {promise} - {@link SavedObjectsClosePointInTimeResponse} + */ + closePointInTime( + id: string, + options?: SavedObjectsClosePointInTimeOptions + ): Promise; + + /** + * Returns a {@link ISavedObjectsPointInTimeFinder} to help page through + * large sets of saved objects. We strongly recommend using this API for + * any `find` queries that might return more than 1000 saved objects, + * however this API is only intended for use in server-side "batch" + * processing of objects where you are collecting all objects in memory + * or streaming them back to the client. + * + * Do NOT use this API in a route handler to facilitate paging through + * saved objects on the client-side unless you are streaming all of the + * results back to the client at once. Because the returned generator is + * stateful, you cannot rely on subsequent http requests retrieving new + * pages from the same Kibana server in multi-instance deployments. + * + * This generator wraps calls to {@link SavedObjectsRepository.find} and + * iterates over multiple pages of results using `_pit` and `search_after`. + * This will open a new Point-In-Time (PIT), and continue paging until a + * set of results is received that's smaller than the designated `perPage`. + * + * Once you have retrieved all of the results you need, it is recommended + * to call `close()` to clean up the PIT and prevent Elasticsearch from + * consuming resources unnecessarily. This is only required if you are + * done iterating and have not yet paged through all of the results: the + * PIT will automatically be closed for you once you reach the last page + * of results, or if the underlying call to `find` fails for any reason. + * + * @example + * ```ts + * const findOptions: SavedObjectsCreatePointInTimeFinderOptions = { + * type: 'visualization', + * search: 'foo*', + * perPage: 100, + * }; + * + * const finder = savedObjectsClient.createPointInTimeFinder(findOptions); + * + * const responses: SavedObjectFindResponse[] = []; + * for await (const response of finder.find()) { + * responses.push(...response); + * if (doneSearching) { + * await finder.close(); + * } + * } + * ``` + */ + createPointInTimeFinder( + findOptions: SavedObjectsCreatePointInTimeFinderOptions, + dependencies?: SavedObjectsCreatePointInTimeFinderDependencies + ): ISavedObjectsPointInTimeFinder; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-server/tsconfig.json b/packages/core/saved-objects/core-saved-objects-api-server/tsconfig.json new file mode 100644 index 0000000000000..39d3c7097814a --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-server/tsconfig.json @@ -0,0 +1,18 @@ +{ + "extends": "../../../../tsconfig.bazel.json", + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "emitDeclarationOnly": true, + "outDir": "target_types", + "rootDir": "src", + "stripInternal": false, + "types": [ + "jest", + "node" + ] + }, + "include": [ + "src/**/*" + ] +} diff --git a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts index 43f3bdaaa0921..74840768b8a77 100644 --- a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts +++ b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts @@ -38,73 +38,7 @@ const MAX_REFERENCE_GRAPH_DEPTH = 20; */ export const ALIAS_OR_SHARED_ORIGIN_SEARCH_PER_PAGE = 100; -/** - * An object to collect references for. It must be a multi-namespace type (in other words, the object type must be registered with the - * `namespaceType: 'multiple'` or `namespaceType: 'multiple-isolated'` option). - * - * Note: if options.purpose is 'updateObjectsSpaces', it must be a shareable type (in other words, the object type must be registered with - * the `namespaceType: 'multiple'`). - * - * @public - */ -export interface SavedObjectsCollectMultiNamespaceReferencesObject { - id: string; - type: string; -} - -/** - * Options for collecting references. - * - * @public - */ -export interface SavedObjectsCollectMultiNamespaceReferencesOptions - extends SavedObjectsBaseOptions { - /** Optional purpose used to determine filtering and authorization checks; default is 'collectMultiNamespaceReferences' */ - purpose?: 'collectMultiNamespaceReferences' | 'updateObjectsSpaces'; -} -/** - * A returned input object or one of its references, with additional context. - * - * @public - */ -export interface SavedObjectReferenceWithContext { - /** The type of the referenced object */ - type: string; - /** The ID of the referenced object */ - id: string; - /** The origin ID of the referenced object (if it has one) */ - originId?: string; - /** The space(s) that the referenced object exists in */ - spaces: string[]; - /** - * References to this object; note that this does not contain _all inbound references everywhere for this object_, it only contains - * inbound references for the scope of this operation - */ - inboundReferences: Array<{ - /** The type of the object that has the inbound reference */ - type: string; - /** The ID of the object that has the inbound reference */ - id: string; - /** The name of the inbound reference */ - name: string; - }>; - /** Whether or not this object or reference is missing */ - isMissing?: boolean; - /** The space(s) that legacy URL aliases matching this type/id exist in */ - spacesWithMatchingAliases?: string[]; - /** The space(s) that objects matching this origin exist in (including this one) */ - spacesWithMatchingOrigins?: string[]; -} - -/** - * The response when object references are collected. - * - * @public - */ -export interface SavedObjectsCollectMultiNamespaceReferencesResponse { - objects: SavedObjectReferenceWithContext[]; -} /** * Parameters for the collectMultiNamespaceReferences function. diff --git a/src/core/server/saved_objects/service/lib/point_in_time_finder.ts b/src/core/server/saved_objects/service/lib/point_in_time_finder.ts index b00bfde8d08aa..94cd36d5a7263 100644 --- a/src/core/server/saved_objects/service/lib/point_in_time_finder.ts +++ b/src/core/server/saved_objects/service/lib/point_in_time_finder.ts @@ -15,20 +15,9 @@ type PointInTimeFinderClient = Pick< 'find' | 'openPointInTimeForType' | 'closePointInTime' >; -/** - * @public - */ -export type SavedObjectsCreatePointInTimeFinderOptions = Omit< - SavedObjectsFindOptions, - 'page' | 'pit' | 'searchAfter' ->; -/** - * @public - */ -export interface SavedObjectsCreatePointInTimeFinderDependencies { - client: Pick; -} + + /** * @internal @@ -45,27 +34,6 @@ export type CreatePointInTimeFinderFn = ( findOptions: SavedObjectsCreatePointInTimeFinderOptions ) => ISavedObjectsPointInTimeFinder; -/** @public */ -export interface ISavedObjectsPointInTimeFinder { - /** - * An async generator which wraps calls to `savedObjectsClient.find` and - * iterates over multiple pages of results using `_pit` and `search_after`. - * This will open a new Point-In-Time (PIT), and continue paging until a set - * of results is received that's smaller than the designated `perPage` size. - */ - find: () => AsyncGenerator>; - /** - * Closes the Point-In-Time associated with this finder instance. - * - * Once you have retrieved all of the results you need, it is recommended - * to call `close()` to clean up the PIT and prevent Elasticsearch from - * consuming resources unnecessarily. This is only required if you are - * done iterating and have not yet paged through all of the results: the - * PIT will automatically be closed for you once you reach the last page - * of results, or if the underlying call to `find` fails for any reason. - */ - close: () => Promise; -} /** * @internal diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index e6197ca56ec36..fe492fa3ac98e 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -122,479 +122,14 @@ export interface SavedObjectsRepositoryOptions { logger: Logger; } -/** - * @public - */ -export interface SavedObjectsIncrementCounterOptions - extends SavedObjectsBaseOptions { - /** - * (default=false) If true, sets all the counter fields to 0 if they don't - * already exist. Existing fields will be left as-is and won't be incremented. - */ - initialize?: boolean; - /** {@link SavedObjectsMigrationVersion} */ - migrationVersion?: SavedObjectsMigrationVersion; - /** - * (default='wait_for') The Elasticsearch refresh setting for this - * operation. See {@link MutatingOperationRefreshSetting} - */ - refresh?: MutatingOperationRefreshSetting; - /** - * Attributes to use when upserting the document if it doesn't exist. - */ - upsertAttributes?: Attributes; -} -/** - * - * @public - */ -export interface SavedObjectsDeleteByNamespaceOptions extends SavedObjectsBaseOptions { - /** The Elasticsearch supports only boolean flag for this operation */ - refresh?: boolean; -} -export const DEFAULT_REFRESH_SETTING = 'wait_for'; -export const DEFAULT_RETRY_COUNT = 3; - -/** - * See {@link SavedObjectsRepository} - * - * @public - */ -export interface ISavedObjectsRepository { - /** - * Persists an object - * - * @param {string} type - * @param {object} attributes - * @param {object} [options={}] - * @property {string} [options.id] - force id on creation, not recommended - * @property {boolean} [options.overwrite=false] - * @property {object} [options.migrationVersion=undefined] - * @property {string} [options.namespace] - * @property {array} [options.references=[]] - [{ name, type, id }] - * @returns {promise} - { id, type, version, attributes } - */ - create( - type: string, - attributes: T, - options?: SavedObjectsCreateOptions - ): Promise>; - - /** - * Creates multiple documents at once - * - * @param {array} objects - [{ type, id, attributes, references, migrationVersion }] - * @param {object} [options={}] - * @property {boolean} [options.overwrite=false] - overwrites existing documents - * @property {string} [options.namespace] - * @returns {promise} - {saved_objects: [[{ id, type, version, references, attributes, error: { message } }]} - */ - bulkCreate( - objects: Array>, - options?: SavedObjectsCreateOptions - ): Promise>; - - /** - * Check what conflicts will result when creating a given array of saved objects. This includes "unresolvable conflicts", which are - * multi-namespace objects that exist in a different namespace; such conflicts cannot be resolved/overwritten. - */ - checkConflicts( - objects: SavedObjectsCheckConflictsObject[], - options?: SavedObjectsBaseOptions - ): Promise; - - /** - * Deletes an object - * - * @param {string} type - * @param {string} id - * @param {object} [options={}] - * @property {string} [options.namespace] - * @returns {promise} - */ - delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>; - /** - * Deletes all objects from the provided namespace. - * - * @param {string} namespace - * @returns {promise} - { took, timed_out, total, deleted, batches, version_conflicts, noops, retries, failures } - */ - deleteByNamespace( - namespace: string, - options?: SavedObjectsDeleteByNamespaceOptions - ): Promise; - - /** - * @param {object} [options={}] - * @property {(string|Array)} [options.type] - * @property {string} [options.search] - * @property {string} [options.defaultSearchOperator] - * @property {Array} [options.searchFields] - see Elasticsearch Simple Query String - * Query field argument for more information - * @property {integer} [options.page=1] - * @property {integer} [options.perPage=20] - * @property {Array} [options.searchAfter] - * @property {string} [options.sortField] - * @property {string} [options.sortOrder] - * @property {Array} [options.fields] - * @property {string} [options.namespace] - * @property {object} [options.hasReference] - { type, id } - * @property {string} [options.pit] - * @property {string} [options.preference] - * @returns {promise} - { saved_objects: [{ id, type, version, attributes }], total, per_page, page } - */ - find( - options: SavedObjectsFindOptions - ): Promise>; - - /** - * Returns an array of objects by id - * - * @param {array} objects - an array of objects containing id, type and optionally fields - * @param {object} [options={}] - * @property {string} [options.namespace] - * @returns {promise} - { saved_objects: [{ id, type, version, attributes }] } - * @example - * - * bulkGet([ - * { id: 'one', type: 'config' }, - * { id: 'foo', type: 'index-pattern' } - * ]) - */ - bulkGet( - objects: SavedObjectsBulkGetObject[], - options?: SavedObjectsBaseOptions - ): Promise>; - - /** - * Resolves an array of objects by id, using any legacy URL aliases if they exist - * - * @param {array} objects - an array of objects containing id, type - * @param {object} [options={}] - * @property {string} [options.namespace] - * @returns {promise} - { resolved_objects: [{ saved_object, outcome }] } - * @example - * - * bulkResolve([ - * { id: 'one', type: 'config' }, - * { id: 'foo', type: 'index-pattern' } - * ]) - */ - bulkResolve( - objects: SavedObjectsBulkResolveObject[], - options?: SavedObjectsBaseOptions - ): Promise>; - - /** - * Gets a single object - * - * @param {string} type - * @param {string} id - * @param {object} [options={}] - * @property {string} [options.namespace] - * @returns {promise} - { id, type, version, attributes } - */ - get( - type: string, - id: string, - options?: SavedObjectsBaseOptions - ): Promise>; - - /** - * Resolves a single object, using any legacy URL alias if it exists - * - * @param {string} type - * @param {string} id - * @param {object} [options={}] - * @property {string} [options.namespace] - * @returns {promise} - { saved_object, outcome } - */ - resolve( - type: string, - id: string, - options?: SavedObjectsBaseOptions - ): Promise>; - - /** - * Updates an object - * - * @param {string} type - * @param {string} id - * @param {object} [options={}] - * @property {string} options.version - ensures version matches that of persisted object - * @property {string} [options.namespace] - * @property {array} [options.references] - [{ name, type, id }] - * @returns {promise} - */ - update( - type: string, - id: string, - attributes: Partial, - options?: SavedObjectsUpdateOptions - ): Promise>; - /** - * Gets all references and transitive references of the given objects. Ignores any object and/or reference that is not a multi-namespace - * type. - * - * @param objects The objects to get the references for. - */ - collectMultiNamespaceReferences( - objects: SavedObjectsCollectMultiNamespaceReferencesObject[], - options?: SavedObjectsCollectMultiNamespaceReferencesOptions - ): Promise; - - /** - * Updates one or more objects to add and/or remove them from specified spaces. - * - * @param objects - * @param spacesToAdd - * @param spacesToRemove - * @param options - */ - updateObjectsSpaces( - objects: SavedObjectsUpdateObjectsSpacesObject[], - spacesToAdd: string[], - spacesToRemove: string[], - options?: SavedObjectsUpdateObjectsSpacesOptions - ): Promise; - - /** - * Updates multiple objects in bulk - * - * @param {array} objects - [{ type, id, attributes, options: { version, namespace } references }] - * @property {string} options.version - ensures version matches that of persisted object - * @property {string} [options.namespace] - * @returns {promise} - {saved_objects: [[{ id, type, version, references, attributes, error: { message } }]} - */ - bulkUpdate( - objects: Array>, - options?: SavedObjectsBulkUpdateOptions - ): Promise>; - - /** - * Updates all objects containing a reference to the given {type, id} tuple to remove the said reference. - * - * @remarks Will throw a conflict error if the `update_by_query` operation returns any failure. In that case - * some references might have been removed, and some were not. It is the caller's responsibility - * to handle and fix this situation if it was to happen. - */ - removeReferencesTo( - type: string, - id: string, - options?: SavedObjectsRemoveReferencesToOptions - ): Promise; - - /** - * Increments all the specified counter fields (by one by default). Creates the document - * if one doesn't exist for the given id. - * - * @remarks - * When supplying a field name like `stats.api.counter` the field name will - * be used as-is to create a document like: - * `{attributes: {'stats.api.counter': 1}}` - * It will not create a nested structure like: - * `{attributes: {stats: {api: {counter: 1}}}}` - * - * When using incrementCounter for collecting usage data, you need to ensure - * that usage collection happens on a best-effort basis and doesn't - * negatively affect your plugin or users. See https://github.com/elastic/kibana/blob/main/src/plugins/usage_collection/README.mdx#tracking-interactions-with-incrementcounter) - * - * @example - * ```ts - * const repository = coreStart.savedObjects.createInternalRepository(); - * - * // Initialize all fields to 0 - * repository - * .incrementCounter('dashboard_counter_type', 'counter_id', [ - * 'stats.apiCalls', - * 'stats.sampleDataInstalled', - * ], {initialize: true}); - * - * // Increment the apiCalls field counter - * repository - * .incrementCounter('dashboard_counter_type', 'counter_id', [ - * 'stats.apiCalls', - * ]) - * - * // Increment the apiCalls field counter by 4 - * repository - * .incrementCounter('dashboard_counter_type', 'counter_id', [ - * { fieldName: 'stats.apiCalls' incrementBy: 4 }, - * ]) - * - * // Initialize the document with arbitrary fields if not present - * repository.incrementCounter<{ appId: string }>( - * 'dashboard_counter_type', - * 'counter_id', - * [ 'stats.apiCalls'], - * { upsertAttributes: { appId: 'myId' } } - * ) - * ``` - * - * @param type - The type of saved object whose fields should be incremented - * @param id - The id of the document whose fields should be incremented - * @param counterFields - An array of field names to increment or an array of {@link SavedObjectsIncrementCounterField} - * @param options - {@link SavedObjectsIncrementCounterOptions} - * @returns The saved object after the specified fields were incremented - */ - incrementCounter( - type: string, - id: string, - counterFields: Array, - options?: SavedObjectsIncrementCounterOptions - ): Promise>; - - /** - * Opens a Point In Time (PIT) against the indices for the specified Saved Object types. - * The returned `id` can then be passed to `SavedObjects.find` to search against that PIT. - * - * Only use this API if you have an advanced use case that's not solved by the - * {@link SavedObjectsRepository.createPointInTimeFinder} method. - * - * @example - * ```ts - * const { id } = await savedObjectsClient.openPointInTimeForType( - * type: 'visualization', - * { keepAlive: '5m' }, - * ); - * const page1 = await savedObjectsClient.find({ - * type: 'visualization', - * sortField: 'updated_at', - * sortOrder: 'asc', - * pit: { id, keepAlive: '2m' }, - * }); - * const lastHit = page1.saved_objects[page1.saved_objects.length - 1]; - * const page2 = await savedObjectsClient.find({ - * type: 'visualization', - * sortField: 'updated_at', - * sortOrder: 'asc', - * pit: { id: page1.pit_id }, - * searchAfter: lastHit.sort, - * }); - * await savedObjectsClient.closePointInTime(page2.pit_id); - * ``` - * - * @param {string|Array} type - * @param {object} [options] - {@link SavedObjectsOpenPointInTimeOptions} - * @property {string} [options.keepAlive] - * @property {string} [options.preference] - * @returns {promise} - { id: string } - */ - openPointInTimeForType( - type: string | string[], - options?: SavedObjectsOpenPointInTimeOptions - ): Promise; - - /** - * Closes a Point In Time (PIT) by ID. This simply proxies the request to ES - * via the Elasticsearch client, and is included in the Saved Objects Client - * as a convenience for consumers who are using `openPointInTimeForType`. - * - * Only use this API if you have an advanced use case that's not solved by the - * {@link SavedObjectsRepository.createPointInTimeFinder} method. - * - * @remarks - * While the `keepAlive` that is provided will cause a PIT to automatically close, - * it is highly recommended to explicitly close a PIT when you are done with it - * in order to avoid consuming unneeded resources in Elasticsearch. - * - * @example - * ```ts - * const repository = coreStart.savedObjects.createInternalRepository(); - * - * const { id } = await repository.openPointInTimeForType( - * type: 'index-pattern', - * { keepAlive: '2m' }, - * ); - * - * const response = await repository.find({ - * type: 'index-pattern', - * search: 'foo*', - * sortField: 'name', - * sortOrder: 'desc', - * pit: { - * id: 'abc123', - * keepAlive: '2m', - * }, - * searchAfter: [1234, 'abcd'], - * }); - * - * await repository.closePointInTime(response.pit_id); - * ``` - * - * @param {string} id - * @param {object} [options] - {@link SavedObjectsClosePointInTimeOptions} - * @returns {promise} - {@link SavedObjectsClosePointInTimeResponse} - */ - closePointInTime( - id: string, - options?: SavedObjectsClosePointInTimeOptions - ): Promise; +export const DEFAULT_REFRESH_SETTING = 'wait_for'; +export const DEFAULT_RETRY_COUNT = 3; - /** - * Returns a {@link ISavedObjectsPointInTimeFinder} to help page through - * large sets of saved objects. We strongly recommend using this API for - * any `find` queries that might return more than 1000 saved objects, - * however this API is only intended for use in server-side "batch" - * processing of objects where you are collecting all objects in memory - * or streaming them back to the client. - * - * Do NOT use this API in a route handler to facilitate paging through - * saved objects on the client-side unless you are streaming all of the - * results back to the client at once. Because the returned generator is - * stateful, you cannot rely on subsequent http requests retrieving new - * pages from the same Kibana server in multi-instance deployments. - * - * This generator wraps calls to {@link SavedObjectsRepository.find} and - * iterates over multiple pages of results using `_pit` and `search_after`. - * This will open a new Point-In-Time (PIT), and continue paging until a - * set of results is received that's smaller than the designated `perPage`. - * - * Once you have retrieved all of the results you need, it is recommended - * to call `close()` to clean up the PIT and prevent Elasticsearch from - * consuming resources unnecessarily. This is only required if you are - * done iterating and have not yet paged through all of the results: the - * PIT will automatically be closed for you once you reach the last page - * of results, or if the underlying call to `find` fails for any reason. - * - * @example - * ```ts - * const findOptions: SavedObjectsCreatePointInTimeFinderOptions = { - * type: 'visualization', - * search: 'foo*', - * perPage: 100, - * }; - * - * const finder = savedObjectsClient.createPointInTimeFinder(findOptions); - * - * const responses: SavedObjectFindResponse[] = []; - * for await (const response of finder.find()) { - * responses.push(...response); - * if (doneSearching) { - * await finder.close(); - * } - * } - * ``` - */ - createPointInTimeFinder( - findOptions: SavedObjectsCreatePointInTimeFinderOptions, - dependencies?: SavedObjectsCreatePointInTimeFinderDependencies - ): ISavedObjectsPointInTimeFinder; -} -/** - * @public - */ -export interface SavedObjectsIncrementCounterField { - /** The field name to increment the counter by.*/ - fieldName: string; - /** The number to increment the field by (defaults to 1).*/ - incrementBy?: number; -} /** * @internal diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts index 3b072490acf31..d7d7e7aa5ca23 100644 --- a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts +++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts @@ -33,64 +33,7 @@ import { ALL_NAMESPACES_STRING } from './utils'; import type { DeleteLegacyUrlAliasesParams } from './legacy_url_aliases'; import { deleteLegacyUrlAliases } from './legacy_url_aliases'; -/** - * An object that should have its spaces updated. - * - * @public - */ -export interface SavedObjectsUpdateObjectsSpacesObject { - /** The type of the object to update */ - id: string; - /** The ID of the object to update */ - type: string; - /** - * The space(s) that the object to update currently exists in. This is only intended to be used by SOC wrappers. - * - * @internal - */ - spaces?: string[]; - /** - * The version of the object to update; this is used for optimistic concurrency control. This is only intended to be used by SOC wrappers. - * - * @internal - */ - version?: string; -} - -/** - * Options for the update operation. - * - * @public - */ -export interface SavedObjectsUpdateObjectsSpacesOptions extends SavedObjectsBaseOptions { - /** The Elasticsearch Refresh setting for this operation */ - refresh?: MutatingOperationRefreshSetting; -} -/** - * The response when objects' spaces are updated. - * - * @public - */ -export interface SavedObjectsUpdateObjectsSpacesResponse { - objects: SavedObjectsUpdateObjectsSpacesResponseObject[]; -} - -/** - * Details about a specific object's update result. - * - * @public - */ -export interface SavedObjectsUpdateObjectsSpacesResponseObject { - /** The type of the referenced object */ - type: string; - /** The ID of the referenced object */ - id: string; - /** The space(s) that the referenced object exists in */ - spaces: string[]; - /** Included if there was an error updating this object's spaces */ - error?: SavedObjectError; -} /** * Parameters for the updateObjectsSpaces function. diff --git a/src/core/server/saved_objects/service/saved_objects_client.ts b/src/core/server/saved_objects/service/saved_objects_client.ts index aab310beab214..1aa950e8a832c 100644 --- a/src/core/server/saved_objects/service/saved_objects_client.ts +++ b/src/core/server/saved_objects/service/saved_objects_client.ts @@ -31,723 +31,6 @@ import { import { SavedObjectsErrorHelpers } from './lib/errors'; import { SavedObjectsUpdateObjectsSpacesResponse } from './lib'; -/** - * - * @public - */ -export interface SavedObjectsCreateOptions extends SavedObjectsBaseOptions { - /** (not recommended) Specify an id for the document */ - id?: string; - /** Overwrite existing documents (defaults to false) */ - overwrite?: boolean; - /** - * An opaque version number which changes on each successful write operation. - * Can be used in conjunction with `overwrite` for implementing optimistic concurrency control. - **/ - version?: string; - /** {@inheritDoc SavedObjectsMigrationVersion} */ - migrationVersion?: SavedObjectsMigrationVersion; - /** - * A semver value that is used when upgrading objects between Kibana versions. If undefined, this will be automatically set to the current - * Kibana version when the object is created. If this is set to a non-semver value, or it is set to a semver value greater than the - * current Kibana version, it will result in an error. - * - * @remarks - * Do not attempt to set this manually. It should only be used if you retrieved an existing object that had the `coreMigrationVersion` - * field set and you want to create it again. - */ - coreMigrationVersion?: string; - references?: SavedObjectReference[]; - /** The Elasticsearch Refresh setting for this operation */ - refresh?: MutatingOperationRefreshSetting; - /** Optional ID of the original saved object, if this object's `id` was regenerated */ - originId?: string; - /** - * Optional initial namespaces for the object to be created in. If this is defined, it will supersede the namespace ID that is in - * {@link SavedObjectsCreateOptions}. - * - * * For shareable object types (registered with `namespaceType: 'multiple'`): this option can be used to specify one or more spaces, - * including the "All spaces" identifier (`'*'`). - * * For isolated object types (registered with `namespaceType: 'single'` or `namespaceType: 'multiple-isolated'`): this option can only - * be used to specify a single space, and the "All spaces" identifier (`'*'`) is not allowed. - * * For global object types (registered with `namespaceType: 'agnostic'`): this option cannot be used. - */ - initialNamespaces?: string[]; -} - -/** - * - * @public - */ -export interface SavedObjectsBulkCreateObject { - id?: string; - type: string; - attributes: T; - version?: string; - references?: SavedObjectReference[]; - /** {@inheritDoc SavedObjectsMigrationVersion} */ - migrationVersion?: SavedObjectsMigrationVersion; - /** - * A semver value that is used when upgrading objects between Kibana versions. If undefined, this will be automatically set to the current - * Kibana version when the object is created. If this is set to a non-semver value, or it is set to a semver value greater than the - * current Kibana version, it will result in an error. - * - * @remarks - * Do not attempt to set this manually. It should only be used if you retrieved an existing object that had the `coreMigrationVersion` - * field set and you want to create it again. - */ - coreMigrationVersion?: string; - /** Optional ID of the original saved object, if this object's `id` was regenerated */ - originId?: string; - /** - * Optional initial namespaces for the object to be created in. If this is defined, it will supersede the namespace ID that is in - * {@link SavedObjectsCreateOptions}. - * - * * For shareable object types (registered with `namespaceType: 'multiple'`): this option can be used to specify one or more spaces, - * including the "All spaces" identifier (`'*'`). - * * For isolated object types (registered with `namespaceType: 'single'` or `namespaceType: 'multiple-isolated'`): this option can only - * be used to specify a single space, and the "All spaces" identifier (`'*'`) is not allowed. - * * For global object types (registered with `namespaceType: 'agnostic'`): this option cannot be used. - */ - initialNamespaces?: string[]; -} - -/** - * - * @public - */ -export interface SavedObjectsBulkUpdateObject - extends Pick, 'version' | 'references'> { - /** The ID of this Saved Object, guaranteed to be unique for all objects of the same `type` */ - id: string; - /** The type of this Saved Object. Each plugin can define it's own custom Saved Object types. */ - type: string; - /** {@inheritdoc SavedObjectAttributes} */ - attributes: Partial; - /** - * Optional namespace string to use when searching for this object. If this is defined, it will supersede the namespace ID that is in - * {@link SavedObjectsBulkUpdateOptions}. - * - * Note: the default namespace's string representation is `'default'`, and its ID representation is `undefined`. - **/ - namespace?: string; -} - -/** - * - * @public - */ -export interface SavedObjectsBulkResponse { - saved_objects: Array>; -} - -/** - * - * @public - */ -export interface SavedObjectsFindResult extends SavedObject { - /** - * The Elasticsearch `_score` of this result. - */ - score: number; - /** - * The Elasticsearch `sort` value of this result. - * - * @remarks - * This can be passed directly to the `searchAfter` param in the {@link SavedObjectsFindOptions} - * in order to page through large numbers of hits. It is recommended you use this alongside - * a Point In Time (PIT) that was opened with {@link SavedObjectsClient.openPointInTimeForType}. - * - * @example - * ```ts - * const { id } = await savedObjectsClient.openPointInTimeForType('visualization'); - * const page1 = await savedObjectsClient.find({ - * type: 'visualization', - * sortField: 'updated_at', - * sortOrder: 'asc', - * pit: { id }, - * }); - * const lastHit = page1.saved_objects[page1.saved_objects.length - 1]; - * const page2 = await savedObjectsClient.find({ - * type: 'visualization', - * sortField: 'updated_at', - * sortOrder: 'asc', - * pit: { id: page1.pit_id }, - * searchAfter: lastHit.sort, - * }); - * await savedObjectsClient.closePointInTime(page2.pit_id); - * ``` - */ - sort?: string[]; -} - -/** - * Return type of the Saved Objects `find()` method. - * - * *Note*: this type is different between the Public and Server Saved Objects - * clients. - * - * @public - */ -export interface SavedObjectsFindResponse { - aggregations?: A; - saved_objects: Array>; - total: number; - per_page: number; - page: number; - pit_id?: string; -} - -/** - * - * @public - */ -export interface SavedObjectsCheckConflictsObject { - id: string; - type: string; -} - -/** - * - * @public - */ -export interface SavedObjectsCheckConflictsResponse { - errors: Array<{ - id: string; - type: string; - error: SavedObjectError; - }>; -} - -/** - * - * @public - */ -export interface SavedObjectsUpdateOptions extends SavedObjectsBaseOptions { - /** - * An opaque version number which changes on each successful write operation. - * Can be used for implementing optimistic concurrency control. - */ - version?: string; - /** {@inheritdoc SavedObjectReference} */ - references?: SavedObjectReference[]; - /** The Elasticsearch Refresh setting for this operation */ - refresh?: MutatingOperationRefreshSetting; - /** If specified, will be used to perform an upsert if the document doesn't exist */ - upsert?: Attributes; - /** - * The Elasticsearch `retry_on_conflict` setting for this operation. - * Defaults to `0` when `version` is provided, `3` otherwise. - */ - retryOnConflict?: number; -} - -/** - * - * @public - */ -export interface SavedObjectsRemoveReferencesToOptions extends SavedObjectsBaseOptions { - /** The Elasticsearch Refresh setting for this operation. Defaults to `true` */ - refresh?: boolean; -} - -/** - * - * @public - */ -export interface SavedObjectsRemoveReferencesToResponse extends SavedObjectsBaseOptions { - /** The number of objects that have been updated by this operation */ - updated: number; -} - -/** - * - * @public - */ -export interface SavedObjectsBulkUpdateOptions extends SavedObjectsBaseOptions { - /** The Elasticsearch Refresh setting for this operation */ - refresh?: MutatingOperationRefreshSetting; -} - -/** - * - * @public - */ -export interface SavedObjectsDeleteOptions extends SavedObjectsBaseOptions { - /** The Elasticsearch Refresh setting for this operation */ - refresh?: MutatingOperationRefreshSetting; - /** Force deletion of an object that exists in multiple namespaces */ - force?: boolean; -} - -/** - * - * @public - */ -export interface SavedObjectsBulkGetObject { - id: string; - type: string; - /** SavedObject fields to include in the response */ - fields?: string[]; - /** - * Optional namespace(s) for the object to be retrieved in. If this is defined, it will supersede the namespace ID that is in the - * top-level options. - * - * * For shareable object types (registered with `namespaceType: 'multiple'`): this option can be used to specify one or more spaces, - * including the "All spaces" identifier (`'*'`). - * * For isolated object types (registered with `namespaceType: 'single'` or `namespaceType: 'multiple-isolated'`): this option can only - * be used to specify a single space, and the "All spaces" identifier (`'*'`) is not allowed. - * * For global object types (registered with `namespaceType: 'agnostic'`): this option cannot be used. - */ - namespaces?: string[]; -} - -/** - * - * @public - */ -export interface SavedObjectsBulkResponse { - saved_objects: Array>; -} - -/** - * - * @public - */ -export interface SavedObjectsBulkUpdateResponse { - saved_objects: Array>; -} - -/** - * - * @public - */ -export interface SavedObjectsUpdateResponse - extends Omit, 'attributes' | 'references'> { - attributes: Partial; - references: SavedObjectReference[] | undefined; -} - -/** - * - * @public - */ -export interface SavedObjectsBulkResolveObject { - id: string; - type: string; -} - -/** - * - * @public - */ -export interface SavedObjectsBulkResolveResponse { - resolved_objects: Array>; -} - -/** - * - * @public - */ -export interface SavedObjectsResolveResponse { - /** - * The saved object that was found. - */ - saved_object: SavedObject; - /** - * The outcome for a successful `resolve` call is one of the following values: - * - * * `'exactMatch'` -- One document exactly matched the given ID. - * * `'aliasMatch'` -- One document with a legacy URL alias matched the given ID; in this case the `saved_object.id` field is different - * than the given ID. - * * `'conflict'` -- Two documents matched the given ID, one was an exact match and another with a legacy URL alias; in this case the - * `saved_object` object is the exact match, and the `saved_object.id` field is the same as the given ID. - */ - outcome: 'exactMatch' | 'aliasMatch' | 'conflict'; - /** - * The ID of the object that the legacy URL alias points to. - * - * **Note:** this field is *only* included when an alias was found (in other words, when the outcome is `'aliasMatch'` or `'conflict'`). - */ - alias_target_id?: string; - /** - * The reason this alias was created. - * - * Currently this is used to determine whether or not a toast should be shown when a user is redirected from a legacy URL; if the alias - * was created because of saved object conversion, then we will display a toast telling the user that the object has a new URL. - * - * **Note:** this field is *only* included when an alias was found (in other words, when the outcome is `'aliasMatch'` or `'conflict'`). - */ - alias_purpose?: 'savedObjectConversion' | 'savedObjectImport'; -} - -/** - * @public - */ -export interface SavedObjectsOpenPointInTimeOptions { - /** - * Optionally specify how long ES should keep the PIT alive until the next request. Defaults to `5m`. - */ - keepAlive?: string; - /** - * An optional ES preference value to be used for the query. - */ - preference?: string; - /** - * An optional list of namespaces to be used when opening the PIT. - * - * When the spaces plugin is enabled: - * - this will default to the user's current space (as determined by the URL) - * - if specified, the user's current space will be ignored - * - `['*']` will search across all available spaces - */ - namespaces?: string[]; -} - -/** - * @public - */ -export interface SavedObjectsOpenPointInTimeResponse { - /** - * PIT ID returned from ES. - */ - id: string; -} - -/** - * @public - */ -export type SavedObjectsClosePointInTimeOptions = SavedObjectsBaseOptions; - -/** - * @public - */ -export interface SavedObjectsClosePointInTimeResponse { - /** - * If true, all search contexts associated with the PIT id are - * successfully closed. - */ - succeeded: boolean; - /** - * The number of search contexts that have been successfully closed. - */ - num_freed: number; -} - -/** - * Saved Objects is Kibana's data persisentence mechanism allowing plugins to - * use Elasticsearch for storing plugin state. - * - * ## SavedObjectsClient errors - * - * Since the SavedObjectsClient has its hands in everything we - * are a little paranoid about the way we present errors back to - * to application code. Ideally, all errors will be either: - * - * 1. Caused by bad implementation (ie. undefined is not a function) and - * as such unpredictable - * 2. An error that has been classified and decorated appropriately - * by the decorators in {@link SavedObjectsErrorHelpers} - * - * Type 1 errors are inevitable, but since all expected/handle-able errors - * should be Type 2 the `isXYZError()` helpers exposed at - * `SavedObjectsErrorHelpers` should be used to understand and manage error - * responses from the `SavedObjectsClient`. - * - * Type 2 errors are decorated versions of the source error, so if - * the elasticsearch client threw an error it will be decorated based - * on its type. That means that rather than looking for `error.body.error.type` or - * doing substring checks on `error.body.error.reason`, just use the helpers to - * understand the meaning of the error: - * - * ```js - * if (SavedObjectsErrorHelpers.isNotFoundError(error)) { - * // handle 404 - * } - * - * if (SavedObjectsErrorHelpers.isNotAuthorizedError(error)) { - * // 401 handling should be automatic, but in case you wanted to know - * } - * - * // always rethrow the error unless you handle it - * throw error; - * ``` - * - * ### 404s from missing index - * - * From the perspective of application code and APIs the SavedObjectsClient is - * a black box that persists objects. One of the internal details that users have - * no control over is that we use an elasticsearch index for persistence and that - * index might be missing. - * - * At the time of writing we are in the process of transitioning away from the - * operating assumption that the SavedObjects index is always available. Part of - * this transition is handling errors resulting from an index missing. These used - * to trigger a 500 error in most cases, and in others cause 404s with different - * error messages. - * - * From my (Spencer) perspective, a 404 from the SavedObjectsApi is a 404; The - * object the request/call was targeting could not be found. This is why #14141 - * takes special care to ensure that 404 errors are generic and don't distinguish - * between index missing or document missing. - * - * See {@link SavedObjectsClient} - * See {@link SavedObjectsErrorHelpers} - * - * @public - */ -export interface SavedObjectsClientContract { - /** - * Persists a SavedObject - * - * @param type - * @param attributes - * @param options - */ - create( - type: string, - attributes: T, - options?: SavedObjectsCreateOptions - ): Promise>; - - /** - * Persists multiple documents batched together as a single request - * - * @param objects - * @param options - */ - bulkCreate( - objects: Array>, - options?: SavedObjectsCreateOptions - ): Promise>; - - /** - * Check what conflicts will result when creating a given array of saved objects. This includes "unresolvable conflicts", which are - * multi-namespace objects that exist in a different namespace; such conflicts cannot be resolved/overwritten. - * - * @param objects - * @param options - */ - checkConflicts( - objects: SavedObjectsCheckConflictsObject[], - options?: SavedObjectsBaseOptions - ): Promise; - - /** - * Deletes a SavedObject - * - * @param type - * @param id - * @param options - */ - delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>; - - /** - * Find all SavedObjects matching the search query - * - * @param options - */ - find( - options: SavedObjectsFindOptions - ): Promise>; - - /** - * Returns an array of objects by id - * - * @param objects - an array of ids, or an array of objects containing id, type and optionally fields - * @example - * - * bulkGet([ - * { id: 'one', type: 'config' }, - * { id: 'foo', type: 'index-pattern' } - * ]) - */ - bulkGet( - objects: SavedObjectsBulkGetObject[], - options?: SavedObjectsBaseOptions - ): Promise>; - - /** - * Retrieves a single object - * - * @param type - The type of SavedObject to retrieve - * @param id - The ID of the SavedObject to retrieve - * @param options - */ - get( - type: string, - id: string, - options?: SavedObjectsBaseOptions - ): Promise>; - - /** - * Resolves an array of objects by id, using any legacy URL aliases if they exist - * - * @param objects - an array of objects containing id, type - * @example - * - * bulkResolve([ - * { id: 'one', type: 'config' }, - * { id: 'foo', type: 'index-pattern' } - * ]) - * - * @note Saved objects that Kibana fails to find are replaced with an error object and an "exactMatch" outcome. The rationale behind the - * outcome is that "exactMatch" is the default outcome, and the outcome only changes if an alias is found. This behavior is unique to - * `bulkResolve`; the regular `resolve` API will throw an error instead. - */ - bulkResolve( - objects: SavedObjectsBulkResolveObject[], - options?: SavedObjectsBaseOptions - ): Promise>; - - /** - * Resolves a single object, using any legacy URL alias if it exists - * - * @param type - The type of SavedObject to retrieve - * @param id - The ID of the SavedObject to retrieve - * @param options - */ - resolve( - type: string, - id: string, - options?: SavedObjectsBaseOptions - ): Promise>; - - /** - * Updates an SavedObject - * - * @param type - * @param id - * @param options - */ - update( - type: string, - id: string, - attributes: Partial, - options?: SavedObjectsUpdateOptions - ): Promise>; - - /** - * Bulk Updates multiple SavedObject at once - * - * @param objects - */ - bulkUpdate( - objects: Array>, - options?: SavedObjectsBulkUpdateOptions - ): Promise>; - - /** - * Updates all objects containing a reference to the given {type, id} tuple to remove the said reference. - */ - removeReferencesTo( - type: string, - id: string, - options?: SavedObjectsRemoveReferencesToOptions - ): Promise; - - /** - * Opens a Point In Time (PIT) against the indices for the specified Saved Object types. - * The returned `id` can then be passed to {@link SavedObjectsClient.find} to search - * against that PIT. - * - * Only use this API if you have an advanced use case that's not solved by the - * {@link SavedObjectsClient.createPointInTimeFinder} method. - */ - openPointInTimeForType( - type: string | string[], - options?: SavedObjectsOpenPointInTimeOptions - ): Promise; - - /** - * Closes a Point In Time (PIT) by ID. This simply proxies the request to ES via the - * Elasticsearch client, and is included in the Saved Objects Client as a convenience - * for consumers who are using {@link SavedObjectsClient.openPointInTimeForType}. - * - * Only use this API if you have an advanced use case that's not solved by the - * {@link SavedObjectsClient.createPointInTimeFinder} method. - */ - closePointInTime( - id: string, - options?: SavedObjectsClosePointInTimeOptions - ): Promise; - - /** - * Returns a {@link ISavedObjectsPointInTimeFinder} to help page through - * large sets of saved objects. We strongly recommend using this API for - * any `find` queries that might return more than 1000 saved objects, - * however this API is only intended for use in server-side "batch" - * processing of objects where you are collecting all objects in memory - * or streaming them back to the client. - * - * Do NOT use this API in a route handler to facilitate paging through - * saved objects on the client-side unless you are streaming all of the - * results back to the client at once. Because the returned generator is - * stateful, you cannot rely on subsequent http requests retrieving new - * pages from the same Kibana server in multi-instance deployments. - * - * The generator wraps calls to {@link SavedObjectsClient.find} and iterates - * over multiple pages of results using `_pit` and `search_after`. This will - * open a new Point-In-Time (PIT), and continue paging until a set of - * results is received that's smaller than the designated `perPage`. - * - * Once you have retrieved all of the results you need, it is recommended - * to call `close()` to clean up the PIT and prevent Elasticsearch from - * consuming resources unnecessarily. This is only required if you are - * done iterating and have not yet paged through all of the results: the - * PIT will automatically be closed for you once you reach the last page - * of results, or if the underlying call to `find` fails for any reason. - * - * @example - * ```ts - * const findOptions: SavedObjectsCreatePointInTimeFinderOptions = { - * type: 'visualization', - * search: 'foo*', - * perPage: 100, - * }; - * - * const finder = savedObjectsClient.createPointInTimeFinder(findOptions); - * - * const responses: SavedObjectFindResponse[] = []; - * for await (const response of finder.find()) { - * responses.push(...response); - * if (doneSearching) { - * await finder.close(); - * } - * } - * ``` - */ - createPointInTimeFinder( - findOptions: SavedObjectsCreatePointInTimeFinderOptions, - dependencies?: SavedObjectsCreatePointInTimeFinderDependencies - ): ISavedObjectsPointInTimeFinder; - - /** - * Gets all references and transitive references of the listed objects. Ignores any object that is not a multi-namespace type. - * - * @param objects - * @param options - */ - collectMultiNamespaceReferences( - objects: SavedObjectsCollectMultiNamespaceReferencesObject[], - options?: SavedObjectsCollectMultiNamespaceReferencesOptions - ): Promise; - - /** - * Updates one or more objects to add and/or remove them from specified spaces. - * - * @param objects - * @param spacesToAdd - * @param spacesToRemove - * @param options - */ - updateObjectsSpaces( - objects: SavedObjectsUpdateObjectsSpacesObject[], - spacesToAdd: string[], - spacesToRemove: string[], - options?: SavedObjectsUpdateObjectsSpacesOptions - ): Promise; -} /** * Core internal implementation of {@link SavedObjectsClientContract} diff --git a/src/core/server/saved_objects/types.ts b/src/core/server/saved_objects/types.ts index 5105e063d0cd1..a13097fe23d78 100644 --- a/src/core/server/saved_objects/types.ts +++ b/src/core/server/saved_objects/types.ts @@ -15,8 +15,6 @@ import { SavedObjectsExportTransform } from './export'; import { SavedObjectsImportHook } from './import/types'; import { SavedObjectsValidationMap } from './validation'; -type KueryNode = any; - /** * Meta information about the SavedObjectService's status. Available to plugins via {@link CoreSetup.status}. * @@ -30,120 +28,11 @@ export interface SavedObjectStatusMeta { }; } -/** - * @public - */ -export interface SavedObjectsFindOptionsReference { - type: string; - id: string; -} -/** - * @public - */ -export interface SavedObjectsPitParams { - id: string; - keepAlive?: string; -} -/** - * - * @public - */ -export interface SavedObjectsFindOptions { - type: string | string[]; - page?: number; - perPage?: number; - sortField?: string; - sortOrder?: estypes.SortOrder; - /** - * An array of fields to include in the results - * @example - * SavedObjects.find({type: 'dashboard', fields: ['attributes.name', 'attributes.location']}) - */ - fields?: string[]; - /** Search documents using the Elasticsearch Simple Query String syntax. See Elasticsearch Simple Query String `query` argument for more information */ - search?: string; - /** The fields to perform the parsed query against. See Elasticsearch Simple Query String `fields` argument for more information */ - searchFields?: string[]; - /** - * Use the sort values from the previous page to retrieve the next page of results. - */ - searchAfter?: estypes.Id[]; - /** - * The fields to perform the parsed query against. Unlike the `searchFields` argument, these are expected to be root fields and will not - * be modified. If used in conjunction with `searchFields`, both are concatenated together. - */ - rootSearchFields?: string[]; - /** - * Search for documents having a reference to the specified objects. - * Use `hasReferenceOperator` to specify the operator to use when searching for multiple references. - */ - hasReference?: SavedObjectsFindOptionsReference | SavedObjectsFindOptionsReference[]; - /** - * The operator to use when searching by multiple references using the `hasReference` option. Defaults to `OR` - */ - hasReferenceOperator?: 'AND' | 'OR'; - /** - * The search operator to use with the provided filter. Defaults to `OR` - */ - defaultSearchOperator?: 'AND' | 'OR'; - filter?: string | KueryNode; - /** - * A record of aggregations to perform. - * The API currently only supports a limited set of metrics and bucket aggregation types. - * Additional aggregation types can be contributed to Core. - * - * @example - * Aggregating on SO attribute field - * ```ts - * const aggs = { latest_version: { max: { field: 'dashboard.attributes.version' } } }; - * return client.find({ type: 'dashboard', aggs }) - * ``` - * - * @example - * Aggregating on SO root field - * ```ts - * const aggs = { latest_update: { max: { field: 'dashboard.updated_at' } } }; - * return client.find({ type: 'dashboard', aggs }) - * ``` - * - * @alpha - */ - aggs?: Record; - namespaces?: string[]; - /** - * This map defines each type to search for, and the namespace(s) to search for the type in; this is only intended to be used by a saved - * object client wrapper. - * If this is defined, it supersedes the `type` and `namespaces` fields when building the Elasticsearch query. - * Any types that are not included in this map will be excluded entirely. - * If a type is included but its value is undefined, the operation will search for that type in the Default namespace. - */ - typeToNamespacesMap?: Map; - /** An optional ES preference value to be used for the query **/ - preference?: string; - /** - * Search against a specific Point In Time (PIT) that you've opened with {@link SavedObjectsClient.openPointInTimeForType}. - */ - pit?: SavedObjectsPitParams; -} - -/** - * - * @public - */ -export interface SavedObjectsBaseOptions { - /** Specify the namespace for this operation */ - namespace?: string; -} -/** - * Elasticsearch Refresh setting for mutating operation - * @public - */ -export type MutatingOperationRefreshSetting = boolean | 'wait_for'; export type { SavedObjectsClientContract } from './service/saved_objects_client'; diff --git a/yarn.lock b/yarn.lock index 2795a579c28cb..0fced9dff9676 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3351,6 +3351,10 @@ version "0.0.0" uid "" +"@kbn/core-saved-objects-api-server@link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-server": + version "0.0.0" + uid "" + "@kbn/core-saved-objects-common@link:bazel-bin/packages/core/saved-objects/core-saved-objects-common": version "0.0.0" uid "" @@ -7114,6 +7118,10 @@ version "0.0.0" uid "" +"@types/kbn__core-saved-objects-api-server@link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-server/npm_module_types": + version "0.0.0" + uid "" + "@types/kbn__core-saved-objects-common@link:bazel-bin/packages/core/saved-objects/core-saved-objects-common/npm_module_types": version "0.0.0" uid "" From be595bb0fe4fd6f20437768a2a350c8ff8be8e4b Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 10:37:10 +0200 Subject: [PATCH 11/46] start fixing imports --- .../saved_objects/saved_objects_service.ts | 8 +- .../lib/collect_multi_namespace_references.ts | 9 +- .../server/saved_objects/service/lib/index.ts | 22 +---- .../service/lib/point_in_time_finder.ts | 15 +-- .../saved_objects/service/lib/repository.ts | 95 ++++++++----------- .../service/lib/scoped_client_provider.ts | 2 +- .../service/lib/update_objects_spaces.ts | 10 +- .../service/saved_objects_client.ts | 44 +++++---- src/core/server/saved_objects/types.ts | 8 +- src/core/server/types.ts | 8 +- 10 files changed, 100 insertions(+), 121 deletions(-) diff --git a/src/core/server/saved_objects/saved_objects_service.ts b/src/core/server/saved_objects/saved_objects_service.ts index 2ce3acb63139e..044c588ac70ee 100644 --- a/src/core/server/saved_objects/saved_objects_service.ts +++ b/src/core/server/saved_objects/saved_objects_service.ts @@ -19,6 +19,10 @@ import type { InternalElasticsearchServiceStart, } from '@kbn/core-elasticsearch-server-internal'; import type { SavedObjectAttributes } from '@kbn/core-saved-objects-common'; +import type { + ISavedObjectsRepository, + SavedObjectsClientContract, +} from '@kbn/core-saved-objects-api-server'; import { SavedObjectsClient, SavedObjectsClientProvider, @@ -32,8 +36,8 @@ import { SavedObjectsMigrationConfigType, SavedObjectConfig, } from './saved_objects_config'; -import { SavedObjectsClientContract, SavedObjectsType, SavedObjectStatusMeta } from './types'; -import { ISavedObjectsRepository, SavedObjectsRepository } from './service/lib/repository'; +import { SavedObjectsType, SavedObjectStatusMeta } from './types'; +import { SavedObjectsRepository } from './service/lib/repository'; import { SavedObjectsClientFactoryProvider, SavedObjectsClientWrapperFactory, diff --git a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts index 74840768b8a77..177b8691e803a 100644 --- a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts +++ b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts @@ -8,9 +8,14 @@ import { isNotFoundFromUnsupportedServer } from '@kbn/core-elasticsearch-server-internal'; import type { SavedObject } from '@kbn/core-saved-objects-common'; +import type { + SavedObjectsCollectMultiNamespaceReferencesObject, + SavedObjectsCollectMultiNamespaceReferencesOptions, + SavedObjectsCollectMultiNamespaceReferencesResponse, + SavedObjectReferenceWithContext, +} from '@kbn/core-saved-objects-api-server'; import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import type { SavedObjectsSerializer } from '../../serialization'; -import type { SavedObjectsBaseOptions } from '../../types'; import { SavedObjectsErrorHelpers } from './errors'; import { findLegacyUrlAliases } from './legacy_url_aliases'; import { getRootFields } from './included_fields'; @@ -38,8 +43,6 @@ const MAX_REFERENCE_GRAPH_DEPTH = 20; */ export const ALIAS_OR_SHARED_ORIGIN_SEARCH_PER_PAGE = 100; - - /** * Parameters for the collectMultiNamespaceReferences function. * diff --git a/src/core/server/saved_objects/service/lib/index.ts b/src/core/server/saved_objects/service/lib/index.ts index ec283f3d3741e..aa88b33a5fa5c 100644 --- a/src/core/server/saved_objects/service/lib/index.ts +++ b/src/core/server/saved_objects/service/lib/index.ts @@ -6,15 +6,9 @@ * Side Public License, v 1. */ -export type { ISavedObjectsRepository, SavedObjectsRepository } from './repository'; +export type { SavedObjectsRepository } from './repository'; export { SavedObjectsClientProvider } from './scoped_client_provider'; -export type { - ISavedObjectsPointInTimeFinder, - SavedObjectsCreatePointInTimeFinderOptions, - SavedObjectsCreatePointInTimeFinderDependencies, -} from './point_in_time_finder'; - export type { SavedObjectsClientWrapperFactory, SavedObjectsClientWrapperOptions, @@ -28,18 +22,4 @@ export { SavedObjectsErrorHelpers } from './errors'; export { SavedObjectsUtils } from './utils'; -export type { - SavedObjectsCollectMultiNamespaceReferencesObject, - SavedObjectsCollectMultiNamespaceReferencesOptions, - SavedObjectReferenceWithContext, - SavedObjectsCollectMultiNamespaceReferencesResponse, -} from './collect_multi_namespace_references'; - -export type { - SavedObjectsUpdateObjectsSpacesObject, - SavedObjectsUpdateObjectsSpacesOptions, - SavedObjectsUpdateObjectsSpacesResponse, - SavedObjectsUpdateObjectsSpacesResponseObject, -} from './update_objects_spaces'; - export { getIndexForType } from './get_index_for_type'; diff --git a/src/core/server/saved_objects/service/lib/point_in_time_finder.ts b/src/core/server/saved_objects/service/lib/point_in_time_finder.ts index 94cd36d5a7263..03249c3e2799a 100644 --- a/src/core/server/saved_objects/service/lib/point_in_time_finder.ts +++ b/src/core/server/saved_objects/service/lib/point_in_time_finder.ts @@ -7,18 +7,20 @@ */ import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { Logger } from '@kbn/logging'; -import type { SavedObjectsFindOptions, SavedObjectsClientContract } from '../../types'; -import type { SavedObjectsFindResponse } from '..'; +import type { + SavedObjectsFindOptions, + SavedObjectsFindResponse, + SavedObjectsClientContract, + SavedObjectsCreatePointInTimeFinderDependencies, + SavedObjectsCreatePointInTimeFinderOptions, + ISavedObjectsPointInTimeFinder, +} from '@kbn/core-saved-objects-api-server'; type PointInTimeFinderClient = Pick< SavedObjectsClientContract, 'find' | 'openPointInTimeForType' | 'closePointInTime' >; - - - - /** * @internal */ @@ -34,7 +36,6 @@ export type CreatePointInTimeFinderFn = ( findOptions: SavedObjectsCreatePointInTimeFinderOptions ) => ISavedObjectsPointInTimeFinder; - /** * @internal */ diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index fe492fa3ac98e..cce2caa61c4af 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -15,14 +15,47 @@ import { isSupportedEsServer, isNotFoundFromUnsupportedServer, } from '@kbn/core-elasticsearch-server-internal'; -import type { SavedObject, SavedObjectsMigrationVersion } from '@kbn/core-saved-objects-common'; -import { getRootPropertiesObjects, IndexMapping } from '../../mappings'; -import { +import type { SavedObject } from '@kbn/core-saved-objects-common'; +import type { + ISavedObjectsRepository, + SavedObjectsBaseOptions, + SavedObjectsIncrementCounterOptions, + SavedObjectsDeleteByNamespaceOptions, + SavedObjectsBulkResponse, + SavedObjectsUpdateResponse, + SavedObjectsBulkGetObject, + SavedObjectsBulkResolveObject, + SavedObjectsIncrementCounterField, + SavedObjectsBulkCreateObject, + SavedObjectsBulkResolveResponse, + SavedObjectsCreateOptions, + SavedObjectsFindResponse, + SavedObjectsBulkUpdateResponse, + SavedObjectsUpdateObjectsSpacesOptions, + SavedObjectsCollectMultiNamespaceReferencesOptions, + SavedObjectsRemoveReferencesToResponse, + SavedObjectsCheckConflictsObject, + SavedObjectsCheckConflictsResponse, + SavedObjectsBulkUpdateOptions, + SavedObjectsFindResult, + SavedObjectsRemoveReferencesToOptions, + SavedObjectsDeleteOptions, + SavedObjectsOpenPointInTimeResponse, + SavedObjectsBulkUpdateObject, + SavedObjectsClosePointInTimeResponse, ISavedObjectsPointInTimeFinder, - PointInTimeFinder, - SavedObjectsCreatePointInTimeFinderOptions, SavedObjectsCreatePointInTimeFinderDependencies, -} from './point_in_time_finder'; + SavedObjectsResolveResponse, + SavedObjectsCollectMultiNamespaceReferencesObject, + SavedObjectsUpdateObjectsSpacesObject, + SavedObjectsUpdateOptions, + SavedObjectsOpenPointInTimeOptions, + SavedObjectsClosePointInTimeOptions, + SavedObjectsCreatePointInTimeFinderOptions, + SavedObjectsFindOptions, +} from '@kbn/core-saved-objects-api-server'; +import { getRootPropertiesObjects, IndexMapping } from '../../mappings'; +import { PointInTimeFinder } from './point_in_time_finder'; import { createRepositoryEsClient, RepositoryEsClient } from './repository_es_client'; import { getSearchDsl } from './search_dsl'; import { includedFields } from './included_fields'; @@ -35,37 +68,7 @@ import { SavedObjectsRawDoc, SavedObjectsRawDocSource, } from '../../serialization'; -import { - SavedObjectsBulkCreateObject, - SavedObjectsBulkGetObject, - SavedObjectsBulkResponse, - SavedObjectsBulkUpdateResponse, - SavedObjectsCheckConflictsObject, - SavedObjectsCheckConflictsResponse, - SavedObjectsCreateOptions, - SavedObjectsFindResponse, - SavedObjectsFindResult, - SavedObjectsClosePointInTimeOptions, - SavedObjectsClosePointInTimeResponse, - SavedObjectsOpenPointInTimeOptions, - SavedObjectsOpenPointInTimeResponse, - SavedObjectsUpdateOptions, - SavedObjectsUpdateResponse, - SavedObjectsBulkUpdateObject, - SavedObjectsBulkUpdateOptions, - SavedObjectsDeleteOptions, - SavedObjectsRemoveReferencesToOptions, - SavedObjectsRemoveReferencesToResponse, - SavedObjectsResolveResponse, - SavedObjectsBulkResolveObject, - SavedObjectsBulkResolveResponse, -} from '../saved_objects_client'; import { LEGACY_URL_ALIAS_TYPE } from '../../object_types'; -import { - SavedObjectsBaseOptions, - SavedObjectsFindOptions, - MutatingOperationRefreshSetting, -} from '../../types'; import { SavedObjectsTypeValidator } from '../../validation'; import { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import { internalBulkResolve, InternalBulkResolveError } from './internal_bulk_resolve'; @@ -89,18 +92,8 @@ import { FIND_DEFAULT_PER_PAGE, SavedObjectsUtils, } from './utils'; -import { - collectMultiNamespaceReferences, - SavedObjectsCollectMultiNamespaceReferencesObject, - SavedObjectsCollectMultiNamespaceReferencesOptions, - SavedObjectsCollectMultiNamespaceReferencesResponse, -} from './collect_multi_namespace_references'; -import { - updateObjectsSpaces, - SavedObjectsUpdateObjectsSpacesObject, - SavedObjectsUpdateObjectsSpacesOptions, - SavedObjectsUpdateObjectsSpacesResponse, -} from './update_objects_spaces'; +import { collectMultiNamespaceReferences } from './collect_multi_namespace_references'; +import { updateObjectsSpaces } from './update_objects_spaces'; import { getIndexForType } from './get_index_for_type'; import { preflightCheckForCreate, @@ -122,15 +115,9 @@ export interface SavedObjectsRepositoryOptions { logger: Logger; } - - - - export const DEFAULT_REFRESH_SETTING = 'wait_for'; export const DEFAULT_RETRY_COUNT = 3; - - /** * @internal */ diff --git a/src/core/server/saved_objects/service/lib/scoped_client_provider.ts b/src/core/server/saved_objects/service/lib/scoped_client_provider.ts index 0a535ad199e2b..68aa94a183e77 100644 --- a/src/core/server/saved_objects/service/lib/scoped_client_provider.ts +++ b/src/core/server/saved_objects/service/lib/scoped_client_provider.ts @@ -7,8 +7,8 @@ */ import type { KibanaRequest } from '@kbn/core-http-server'; +import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; import { PriorityCollection } from './priority_collection'; -import { SavedObjectsClientContract } from '../../types'; import { SavedObjectsRepositoryFactory } from '../../saved_objects_service'; import { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts index d7d7e7aa5ca23..6b09d393ef0c2 100644 --- a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts +++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts @@ -12,11 +12,15 @@ import intersection from 'lodash/intersection'; import type { Logger } from '@kbn/logging'; import { isNotFoundFromUnsupportedServer } from '@kbn/core-elasticsearch-server-internal'; -import type { SavedObjectError } from '@kbn/core-saved-objects-common'; +import type { + SavedObjectsUpdateObjectsSpacesObject, + SavedObjectsUpdateObjectsSpacesOptions, + SavedObjectsUpdateObjectsSpacesResponse, + SavedObjectsUpdateObjectsSpacesResponseObject, +} from '@kbn/core-saved-objects-api-server'; import type { IndexMapping } from '../../mappings'; import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import type { SavedObjectsRawDocSource, SavedObjectsSerializer } from '../../serialization'; -import type { MutatingOperationRefreshSetting, SavedObjectsBaseOptions } from '../../types'; import type { DecoratedError } from './errors'; import { SavedObjectsErrorHelpers } from './errors'; import { @@ -33,8 +37,6 @@ import { ALL_NAMESPACES_STRING } from './utils'; import type { DeleteLegacyUrlAliasesParams } from './legacy_url_aliases'; import { deleteLegacyUrlAliases } from './legacy_url_aliases'; - - /** * Parameters for the updateObjectsSpaces function. * diff --git a/src/core/server/saved_objects/service/saved_objects_client.ts b/src/core/server/saved_objects/service/saved_objects_client.ts index 1aa950e8a832c..c9cfd9e720056 100644 --- a/src/core/server/saved_objects/service/saved_objects_client.ts +++ b/src/core/server/saved_objects/service/saved_objects_client.ts @@ -6,31 +6,41 @@ * Side Public License, v 1. */ +import type { SavedObject } from '@kbn/core-saved-objects-common'; import type { - SavedObject, - SavedObjectError, - SavedObjectReference, - SavedObjectsMigrationVersion, -} from '@kbn/core-saved-objects-common'; -import type { + SavedObjectsClientContract, ISavedObjectsRepository, + SavedObjectsBaseOptions, + SavedObjectsBulkResponse, + SavedObjectsUpdateResponse, + SavedObjectsBulkGetObject, + SavedObjectsBulkResolveObject, + SavedObjectsBulkCreateObject, + SavedObjectsBulkResolveResponse, + SavedObjectsCreateOptions, + SavedObjectsFindResponse, + SavedObjectsBulkUpdateResponse, + SavedObjectsUpdateObjectsSpacesOptions, + SavedObjectsCollectMultiNamespaceReferencesOptions, + SavedObjectsCollectMultiNamespaceReferencesResponse, + SavedObjectsCheckConflictsObject, + SavedObjectsCheckConflictsResponse, + SavedObjectsBulkUpdateOptions, + SavedObjectsRemoveReferencesToOptions, + SavedObjectsDeleteOptions, + SavedObjectsBulkUpdateObject, ISavedObjectsPointInTimeFinder, - SavedObjectsCreatePointInTimeFinderOptions, SavedObjectsCreatePointInTimeFinderDependencies, + SavedObjectsResolveResponse, SavedObjectsCollectMultiNamespaceReferencesObject, - SavedObjectsCollectMultiNamespaceReferencesOptions, - SavedObjectsCollectMultiNamespaceReferencesResponse, SavedObjectsUpdateObjectsSpacesObject, - SavedObjectsUpdateObjectsSpacesOptions, -} from './lib'; -import { - SavedObjectsBaseOptions, - MutatingOperationRefreshSetting, + SavedObjectsUpdateOptions, + SavedObjectsOpenPointInTimeOptions, + SavedObjectsClosePointInTimeOptions, + SavedObjectsCreatePointInTimeFinderOptions, SavedObjectsFindOptions, -} from '../types'; +} from '@kbn/core-saved-objects-api-server'; import { SavedObjectsErrorHelpers } from './lib/errors'; -import { SavedObjectsUpdateObjectsSpacesResponse } from './lib'; - /** * Core internal implementation of {@link SavedObjectsClientContract} diff --git a/src/core/server/saved_objects/types.ts b/src/core/server/saved_objects/types.ts index a13097fe23d78..175ab00c2757b 100644 --- a/src/core/server/saved_objects/types.ts +++ b/src/core/server/saved_objects/types.ts @@ -28,13 +28,7 @@ export interface SavedObjectStatusMeta { }; } - - - - - - -export type { SavedObjectsClientContract } from './service/saved_objects_client'; +export type { SavedObjectsClientContract } from '@kbn/core-saved-objects-common'; /** * @public diff --git a/src/core/server/types.ts b/src/core/server/types.ts index 2523321d20068..ddf9a61471bd6 100644 --- a/src/core/server/types.ts +++ b/src/core/server/types.ts @@ -32,21 +32,19 @@ export type { SavedObjectsMigrationVersion, } from '@kbn/core-saved-objects-common'; export type { - SavedObjectStatusMeta, SavedObjectsFindOptionsReference, SavedObjectsFindOptions, SavedObjectsPitParams, SavedObjectsBaseOptions, MutatingOperationRefreshSetting, SavedObjectsClientContract, -} from './saved_objects/types'; -export type { SavedObjectReferenceWithContext, SavedObjectsCollectMultiNamespaceReferencesResponse, -} from './saved_objects/service'; +} from '@kbn/core-saved-objects-api-server'; export type { DomainDeprecationDetails, DeprecationsGetResponse, } from '@kbn/core-deprecations-common'; -export * from './ui_settings/types'; export type { ExternalUrlConfig } from '@kbn/core-http-server-internal'; +export * from './ui_settings/types'; +export type { SavedObjectStatusMeta } from './saved_objects/types'; From bf313f0ff7f942df67ce4131fbffd40c0fcc2b96 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 10:38:04 +0200 Subject: [PATCH 12/46] one more --- src/core/server/saved_objects/index.ts | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/core/server/saved_objects/index.ts b/src/core/server/saved_objects/index.ts index 7a68a8976fdf4..72d791667e163 100644 --- a/src/core/server/saved_objects/index.ts +++ b/src/core/server/saved_objects/index.ts @@ -53,13 +53,6 @@ export type { SavedObjectsRepositoryFactory, } from './saved_objects_service'; -export type { - ISavedObjectsRepository, - SavedObjectsIncrementCounterOptions, - SavedObjectsIncrementCounterField, - SavedObjectsDeleteByNamespaceOptions, -} from './service/lib/repository'; - export type { SavedObjectsFieldMapping, SavedObjectsMappingProperties, From f58e58e00ebed63739615bc2c20f1e42be0e218a Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 10:50:15 +0200 Subject: [PATCH 13/46] fix global re-exports --- src/core/server/index.ts | 71 +++++++++---------- .../server/saved_objects/service/index.ts | 14 +--- 2 files changed, 36 insertions(+), 49 deletions(-) diff --git a/src/core/server/index.ts b/src/core/server/index.ts index 710f027a03906..f62158af035ce 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -284,6 +284,12 @@ export { } from './saved_objects'; export type { + SavedObject, + SavedObjectAttribute, + SavedObjectAttributes, + SavedObjectAttributeSingle, + SavedObjectReference, + SavedObjectsMigrationVersion, SavedObjectsImportConflictError, SavedObjectsImportAmbiguousConflictError, SavedObjectsImportFailure, @@ -307,33 +313,16 @@ export type { SavedObjectsBulkUpdateResponse, SavedObjectsCheckConflictsObject, SavedObjectsCheckConflictsResponse, - SavedObjectsClientProviderOptions, - SavedObjectsClientWrapperFactory, - SavedObjectsClientWrapperOptions, - SavedObjectsClientFactory, - SavedObjectsClientFactoryProvider, SavedObjectsClosePointInTimeOptions, SavedObjectsClosePointInTimeResponse, ISavedObjectsPointInTimeFinder, SavedObjectsCreatePointInTimeFinderDependencies, SavedObjectsCreatePointInTimeFinderOptions, SavedObjectsCreateOptions, - SavedObjectTypeExcludeFromUpgradeFilterHook, - SavedObjectsExportResultDetails, - SavedObjectsExportExcludedObject, SavedObjectsFindResult, SavedObjectsFindResponse, - SavedObjectsImportOptions, - SavedObjectMigrationContext, - SavedObjectsMigrationLogger, SavedObjectsOpenPointInTimeOptions, SavedObjectsOpenPointInTimeResponse, - SavedObjectsRawDoc, - SavedObjectsRawDocParseOptions, - SavedObjectSanitizedDoc, - SavedObjectUnsanitizedDoc, - SavedObjectsRepositoryFactory, - SavedObjectsResolveImportErrorsOptions, SavedObjectsBulkResolveObject, SavedObjectsBulkResolveResponse, SavedObjectsResolveResponse, @@ -349,15 +338,40 @@ export type { SavedObjectsUpdateObjectsSpacesOptions, SavedObjectsUpdateObjectsSpacesResponse, SavedObjectsUpdateObjectsSpacesResponseObject, - SavedObjectsServiceStart, - SavedObjectsServiceSetup, - SavedObjectStatusMeta, SavedObjectsDeleteOptions, ISavedObjectsRepository, - SavedObjectsRepository, SavedObjectsDeleteByNamespaceOptions, SavedObjectsIncrementCounterOptions, SavedObjectsIncrementCounterField, + SavedObjectsBaseOptions, + MutatingOperationRefreshSetting, + SavedObjectsClientContract, + SavedObjectsFindOptions, + SavedObjectsFindOptionsReference, + SavedObjectsPitParams, +} from '@kbn/core-saved-objects-api-server'; +export type { + SavedObjectsClientProviderOptions, + SavedObjectsClientWrapperFactory, + SavedObjectsClientWrapperOptions, + SavedObjectsClientFactory, + SavedObjectsClientFactoryProvider, + SavedObjectTypeExcludeFromUpgradeFilterHook, + SavedObjectsExportResultDetails, + SavedObjectsExportExcludedObject, + SavedObjectsImportOptions, + SavedObjectMigrationContext, + SavedObjectsMigrationLogger, + SavedObjectsRawDoc, + SavedObjectsRawDocParseOptions, + SavedObjectSanitizedDoc, + SavedObjectUnsanitizedDoc, + SavedObjectsRepositoryFactory, + SavedObjectsResolveImportErrorsOptions, + SavedObjectsServiceStart, + SavedObjectsServiceSetup, + SavedObjectStatusMeta, + SavedObjectsRepository, SavedObjectsFieldMapping, SavedObjectsTypeMappingDefinition, SavedObjectsMappingProperties, @@ -419,21 +433,6 @@ export type { DeprecationsDetails } from '@kbn/core-deprecations-common'; export type { AppCategory } from '../types'; export { DEFAULT_APP_CATEGORIES, APP_WRAPPER_CLASS } from '../utils'; -export type { - SavedObject, - SavedObjectAttribute, - SavedObjectAttributes, - SavedObjectAttributeSingle, - SavedObjectReference, - SavedObjectsBaseOptions, - MutatingOperationRefreshSetting, - SavedObjectsClientContract, - SavedObjectsFindOptions, - SavedObjectsFindOptionsReference, - SavedObjectsPitParams, - SavedObjectsMigrationVersion, -} from './types'; - export { ServiceStatusLevels } from './status'; export type { CoreStatus, ServiceStatus, ServiceStatusLevel, StatusServiceSetup } from './status'; diff --git a/src/core/server/saved_objects/service/index.ts b/src/core/server/saved_objects/service/index.ts index 7b4ffcf2dd6cf..f52efbad6bf05 100644 --- a/src/core/server/saved_objects/service/index.ts +++ b/src/core/server/saved_objects/service/index.ts @@ -8,23 +8,11 @@ export { SavedObjectsErrorHelpers, SavedObjectsClientProvider, SavedObjectsUtils } from './lib'; export type { SavedObjectsRepository, - ISavedObjectsPointInTimeFinder, - SavedObjectsCreatePointInTimeFinderOptions, - SavedObjectsCreatePointInTimeFinderDependencies, ISavedObjectsClientProvider, SavedObjectsClientProviderOptions, SavedObjectsClientWrapperFactory, SavedObjectsClientWrapperOptions, SavedObjectsClientFactory, SavedObjectsClientFactoryProvider, - SavedObjectsCollectMultiNamespaceReferencesObject, - SavedObjectsCollectMultiNamespaceReferencesOptions, - SavedObjectReferenceWithContext, - SavedObjectsCollectMultiNamespaceReferencesResponse, - SavedObjectsUpdateObjectsSpacesObject, - SavedObjectsUpdateObjectsSpacesOptions, - SavedObjectsUpdateObjectsSpacesResponse, - SavedObjectsUpdateObjectsSpacesResponseObject, } from './lib'; - -export * from './saved_objects_client'; +export { SavedObjectsClient } from './saved_objects_client'; From 487915fc13a0c6a8e6468443545d4efb1345ba9e Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 10:54:11 +0200 Subject: [PATCH 14/46] fix some browser-side imports --- src/core/public/saved_objects/saved_objects_client.ts | 2 +- src/core/public/saved_objects/types.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/public/saved_objects/saved_objects_client.ts b/src/core/public/saved_objects/saved_objects_client.ts index 8a8e3d547ca8a..413eeaa67db3e 100644 --- a/src/core/public/saved_objects/saved_objects_client.ts +++ b/src/core/public/saved_objects/saved_objects_client.ts @@ -18,7 +18,7 @@ import type { SavedObjectsClientContract as SavedObjectsApi, SavedObjectsFindOptions as SavedObjectFindOptionsServer, SavedObjectsResolveResponse, -} from '../../server'; +} from '@kbn/core-saved-objects-api-server'; import { SimpleSavedObject } from './simple_saved_object'; import type { ResolvedSimpleSavedObject } from './types'; diff --git a/src/core/public/saved_objects/types.ts b/src/core/public/saved_objects/types.ts index 92ecde94973ec..8a643fe4d299a 100644 --- a/src/core/public/saved_objects/types.ts +++ b/src/core/public/saved_objects/types.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import type { SavedObjectsResolveResponse } from '../../server'; +import type { SavedObjectsResolveResponse } from '@kbn/core-saved-objects-api-server'; import { SimpleSavedObject } from './simple_saved_object'; /** From 8a59dffd147ef96184d581b862dfbd47b188ae79 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 11:27:37 +0200 Subject: [PATCH 15/46] fix more violations --- .../service/lib/repository_with_proxy.test.ts | 2 +- .../validation/validator.test.ts | 2 +- .../export/collect_exported_objects.ts | 3 +- .../export/saved_objects_exporter.ts | 6 ++- src/core/server/saved_objects/export/types.ts | 2 +- .../import/lib/check_conflicts.ts | 2 +- .../lib/check_reference_origins.test.ts | 2 +- .../lib/collect_references_deep.test.ts | 2 +- .../server/saved_objects/routes/update.ts | 2 +- ...collect_multi_namespace_references.test.ts | 6 ++- .../lib/find_shared_origin_objects.test.ts | 2 +- .../service/lib/internal_bulk_resolve.test.ts | 6 ++- .../service/lib/internal_bulk_resolve.ts | 16 +++---- .../find_legacy_url_aliases.test.ts | 2 +- .../service/lib/point_in_time_finder.mock.ts | 6 ++- .../service/lib/point_in_time_finder.test.ts | 10 ++-- .../service/lib/repository.mock.ts | 2 +- .../service/lib/repository.test.ts | 48 +++++++++---------- .../service/lib/search_dsl/pit_params.ts | 2 +- .../service/lib/search_dsl/search_dsl.ts | 2 +- .../service/lib/update_objects_spaces.test.ts | 6 +-- .../saved_objects/service/lib/utils.test.ts | 2 +- .../server/saved_objects/service/lib/utils.ts | 6 ++- .../service/saved_objects_client.test.ts | 12 ++--- src/core/server/saved_objects/types.ts | 2 +- .../get_upgradeable_config.test.ts | 2 +- 26 files changed, 78 insertions(+), 77 deletions(-) diff --git a/src/core/server/integration_tests/saved_objects/service/lib/repository_with_proxy.test.ts b/src/core/server/integration_tests/saved_objects/service/lib/repository_with_proxy.test.ts index 3a27af1383244..7581e5f3639a2 100644 --- a/src/core/server/integration_tests/saved_objects/service/lib/repository_with_proxy.test.ts +++ b/src/core/server/integration_tests/saved_objects/service/lib/repository_with_proxy.test.ts @@ -10,7 +10,7 @@ import Hapi from '@hapi/hapi'; import h2o2 from '@hapi/h2o2'; import { URL } from 'url'; import type { SavedObject } from '@kbn/core-saved-objects-common'; -import { ISavedObjectsRepository } from '../../../../saved_objects/service/lib/repository'; +import type { ISavedObjectsRepository } from '@kbn/core-saved-objects-api-server'; import { InternalCoreSetup, InternalCoreStart } from '../../../../internal_types'; import { Root } from '../../../../root'; import * as kbnTestServer from '../../../../../test_helpers/kbn_server'; diff --git a/src/core/server/integration_tests/saved_objects/validation/validator.test.ts b/src/core/server/integration_tests/saved_objects/validation/validator.test.ts index 44d882b0fe80b..59c9cb65c83f2 100644 --- a/src/core/server/integration_tests/saved_objects/validation/validator.test.ts +++ b/src/core/server/integration_tests/saved_objects/validation/validator.test.ts @@ -12,8 +12,8 @@ import Util from 'util'; import { Env } from '@kbn/config'; import { schema } from '@kbn/config-schema'; import { REPO_ROOT } from '@kbn/utils'; +import type { ISavedObjectsRepository } from '@kbn/core-saved-objects-api-server'; import { SavedObjectsType } from '../../../saved_objects/types'; -import { ISavedObjectsRepository } from '../../../saved_objects/service/lib'; import { getEnvOptions } from '@kbn/config-mocks'; import { InternalCoreSetup, InternalCoreStart } from '../../../internal_types'; import { Root } from '../../../root'; diff --git a/src/core/server/saved_objects/export/collect_exported_objects.ts b/src/core/server/saved_objects/export/collect_exported_objects.ts index 4aea6de98fc2d..cec75952afcae 100644 --- a/src/core/server/saved_objects/export/collect_exported_objects.ts +++ b/src/core/server/saved_objects/export/collect_exported_objects.ts @@ -9,7 +9,8 @@ import type { Logger } from '@kbn/logging'; import type { KibanaRequest } from '@kbn/core-http-server'; import type { SavedObject } from '@kbn/core-saved-objects-common'; -import { SavedObjectsClientContract, SavedObjectsExportablePredicate } from '../types'; +import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; +import { SavedObjectsExportablePredicate } from '../types'; import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry'; import type { SavedObjectsExportTransform } from './types'; import { applyExportTransforms } from './apply_export_transforms'; diff --git a/src/core/server/saved_objects/export/saved_objects_exporter.ts b/src/core/server/saved_objects/export/saved_objects_exporter.ts index 19ff024b6f354..7618d5c79def2 100644 --- a/src/core/server/saved_objects/export/saved_objects_exporter.ts +++ b/src/core/server/saved_objects/export/saved_objects_exporter.ts @@ -10,8 +10,10 @@ import type { Readable } from 'stream'; import { createListStream } from '@kbn/utils'; import type { Logger } from '@kbn/logging'; import type { SavedObject } from '@kbn/core-saved-objects-common'; -import type { SavedObjectsClientContract } from '../types'; -import { SavedObjectsFindResult } from '../service'; +import type { + SavedObjectsClientContract, + SavedObjectsFindResult, +} from '@kbn/core-saved-objects-api-server'; import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry'; import { sortObjects } from './sort_objects'; import { diff --git a/src/core/server/saved_objects/export/types.ts b/src/core/server/saved_objects/export/types.ts index 661f9a861c441..ada5f54eba104 100644 --- a/src/core/server/saved_objects/export/types.ts +++ b/src/core/server/saved_objects/export/types.ts @@ -8,7 +8,7 @@ import type { KibanaRequest } from '@kbn/core-http-server'; import type { SavedObject } from '@kbn/core-saved-objects-common'; -import { SavedObjectsFindOptionsReference } from '../types'; +import type { SavedObjectsFindOptionsReference } from '@kbn/core-saved-objects-api-server'; /** @public */ export interface SavedObjectExportBaseOptions { diff --git a/src/core/server/saved_objects/import/lib/check_conflicts.ts b/src/core/server/saved_objects/import/lib/check_conflicts.ts index 2323b2785e756..f4f6082ef18ab 100644 --- a/src/core/server/saved_objects/import/lib/check_conflicts.ts +++ b/src/core/server/saved_objects/import/lib/check_conflicts.ts @@ -13,7 +13,7 @@ import type { SavedObjectError, SavedObjectsImportRetry, } from '@kbn/core-saved-objects-common'; -import { SavedObjectsClientContract } from '../../types'; +import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; import type { ImportStateMap } from './types'; interface CheckConflictsParams { diff --git a/src/core/server/saved_objects/import/lib/check_reference_origins.test.ts b/src/core/server/saved_objects/import/lib/check_reference_origins.test.ts index de162856b9873..a8ddb5b8a063e 100644 --- a/src/core/server/saved_objects/import/lib/check_reference_origins.test.ts +++ b/src/core/server/saved_objects/import/lib/check_reference_origins.test.ts @@ -8,7 +8,7 @@ import { mockCreateOriginQuery } from './check_reference_origins.test.mock'; -import type { SavedObjectsFindResult } from '../../service'; +import type { SavedObjectsFindResult } from '@kbn/core-saved-objects-api-server'; import type { SavedObjectsClientContract } from '../../types'; import { checkReferenceOrigins, CheckReferenceOriginsParams } from './check_reference_origins'; import { savedObjectsClientMock } from '../../../mocks'; diff --git a/src/core/server/saved_objects/routes/legacy_import_export/lib/collect_references_deep.test.ts b/src/core/server/saved_objects/routes/legacy_import_export/lib/collect_references_deep.test.ts index 1c85ceedf90e6..257fa594d2bc7 100644 --- a/src/core/server/saved_objects/routes/legacy_import_export/lib/collect_references_deep.test.ts +++ b/src/core/server/saved_objects/routes/legacy_import_export/lib/collect_references_deep.test.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedObject, SavedObjectAttributes } from '../../../..'; +import type { SavedObject, SavedObjectAttributes } from '@kbn/core-saved-objects-common'; import { savedObjectsClientMock } from '../../../../mocks'; import { collectReferencesDeep } from './collect_references_deep'; diff --git a/src/core/server/saved_objects/routes/update.ts b/src/core/server/saved_objects/routes/update.ts index 3d68c6a698a04..0d9e4b9cdcf46 100644 --- a/src/core/server/saved_objects/routes/update.ts +++ b/src/core/server/saved_objects/routes/update.ts @@ -7,8 +7,8 @@ */ import { schema } from '@kbn/config-schema'; +import type { SavedObjectsUpdateOptions } from '@kbn/core-saved-objects-api-server'; import { InternalCoreUsageDataSetup } from '../../core_usage_data'; -import type { SavedObjectsUpdateOptions } from '../service/saved_objects_client'; import type { InternalSavedObjectRouter } from '../internal_types'; import { catchAndReturnBoomErrors } from './utils'; diff --git a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.ts b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.ts index cc219579d9c0b..d3cf76716e598 100644 --- a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.ts +++ b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.ts @@ -13,13 +13,15 @@ import { } from './collect_multi_namespace_references.test.mock'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; +import type { + SavedObjectsCollectMultiNamespaceReferencesObject, + SavedObjectsCollectMultiNamespaceReferencesOptions, +} from '@kbn/core-saved-objects-api-server'; import { typeRegistryMock } from '../../saved_objects_type_registry.mock'; import { SavedObjectsSerializer } from '../../serialization'; import { ALIAS_OR_SHARED_ORIGIN_SEARCH_PER_PAGE, CollectMultiNamespaceReferencesParams, - SavedObjectsCollectMultiNamespaceReferencesObject, - SavedObjectsCollectMultiNamespaceReferencesOptions, } from './collect_multi_namespace_references'; import { collectMultiNamespaceReferences } from './collect_multi_namespace_references'; import type { CreatePointInTimeFinderFn } from './point_in_time_finder'; diff --git a/src/core/server/saved_objects/service/lib/find_shared_origin_objects.test.ts b/src/core/server/saved_objects/service/lib/find_shared_origin_objects.test.ts index ed6ecf7b33d61..8051fb847036b 100644 --- a/src/core/server/saved_objects/service/lib/find_shared_origin_objects.test.ts +++ b/src/core/server/saved_objects/service/lib/find_shared_origin_objects.test.ts @@ -8,9 +8,9 @@ import type { DeeplyMockedKeys } from '@kbn/utility-types-jest'; +import type { ISavedObjectsRepository } from '@kbn/core-saved-objects-api-server'; import type { CreatePointInTimeFinderFn, PointInTimeFinder } from './point_in_time_finder'; import { savedObjectsPointInTimeFinderMock } from './point_in_time_finder.mock'; -import type { ISavedObjectsRepository } from './repository'; import { savedObjectsRepositoryMock } from './repository.mock'; import { findSharedOriginObjects } from './find_shared_origin_objects'; diff --git a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts index a9fd704247100..ec55ea7725718 100644 --- a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts +++ b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts @@ -14,12 +14,14 @@ import { import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import type { SavedObject } from '@kbn/core-saved-objects-common'; +import type { + SavedObjectsBulkResolveObject, + SavedObjectsBaseOptions, +} from '@kbn/core-saved-objects-api-server'; import { LEGACY_URL_ALIAS_TYPE } from '../../object_types'; import { typeRegistryMock } from '../../saved_objects_type_registry.mock'; import { SavedObjectsSerializer } from '../../serialization'; import { SavedObjectsErrorHelpers } from './errors'; -import { SavedObjectsBulkResolveObject } from '../saved_objects_client'; -import { SavedObjectsBaseOptions } from '../../types'; import { internalBulkResolve, InternalBulkResolveParams } from './internal_bulk_resolve'; import { SavedObjectsUtils } from './utils'; import { normalizeNamespace } from './internal_utils'; diff --git a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts index aa44a320eecf7..5f66251640232 100644 --- a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts +++ b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts @@ -10,6 +10,13 @@ import type { MgetResponseItem } from '@elastic/elasticsearch/lib/api/typesWithB import { isNotFoundFromUnsupportedServer } from '@kbn/core-elasticsearch-server-internal'; import type { SavedObject } from '@kbn/core-saved-objects-common'; +import type { + SavedObjectsBaseOptions, + SavedObjectsBulkResolveObject, + SavedObjectsResolveResponse, + SavedObjectsIncrementCounterField, + SavedObjectsIncrementCounterOptions, +} from '@kbn/core-saved-objects-api-server'; import { CORE_USAGE_STATS_ID, CORE_USAGE_STATS_TYPE, @@ -18,11 +25,6 @@ import { import { LegacyUrlAlias, LEGACY_URL_ALIAS_TYPE } from '../../object_types'; import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import type { SavedObjectsRawDocSource, SavedObjectsSerializer } from '../../serialization'; -import type { SavedObjectsBaseOptions } from '../../types'; -import type { - SavedObjectsBulkResolveObject, - SavedObjectsResolveResponse, -} from '../saved_objects_client'; import { DecoratedError, SavedObjectsErrorHelpers } from './errors'; import { getCurrentTime, @@ -34,10 +36,6 @@ import { isLeft, isRight, } from './internal_utils'; -import { - SavedObjectsIncrementCounterField, - SavedObjectsIncrementCounterOptions, -} from './repository'; import type { RepositoryEsClient } from './repository_es_client'; /** diff --git a/src/core/server/saved_objects/service/lib/legacy_url_aliases/find_legacy_url_aliases.test.ts b/src/core/server/saved_objects/service/lib/legacy_url_aliases/find_legacy_url_aliases.test.ts index f171b0651ffb4..5a9e5affa1f8c 100644 --- a/src/core/server/saved_objects/service/lib/legacy_url_aliases/find_legacy_url_aliases.test.ts +++ b/src/core/server/saved_objects/service/lib/legacy_url_aliases/find_legacy_url_aliases.test.ts @@ -8,10 +8,10 @@ import type { DeeplyMockedKeys } from '@kbn/utility-types-jest'; +import type { ISavedObjectsRepository } from '@kbn/core-saved-objects-api-server'; import { LegacyUrlAlias, LEGACY_URL_ALIAS_TYPE } from '../../../object_types'; import type { CreatePointInTimeFinderFn, PointInTimeFinder } from '../point_in_time_finder'; import { savedObjectsPointInTimeFinderMock } from '../point_in_time_finder.mock'; -import type { ISavedObjectsRepository } from '../repository'; import { savedObjectsRepositoryMock } from '../repository.mock'; import { findLegacyUrlAliases } from './find_legacy_url_aliases'; diff --git a/src/core/server/saved_objects/service/lib/point_in_time_finder.mock.ts b/src/core/server/saved_objects/service/lib/point_in_time_finder.mock.ts index c5ea141486c76..371c45e90c71c 100644 --- a/src/core/server/saved_objects/service/lib/point_in_time_finder.mock.ts +++ b/src/core/server/saved_objects/service/lib/point_in_time_finder.mock.ts @@ -7,8 +7,10 @@ */ import { loggerMock, MockedLogger } from '@kbn/logging-mocks'; -import type { SavedObjectsClientContract } from '../../types'; -import type { ISavedObjectsRepository } from './repository'; +import type { + SavedObjectsClientContract, + ISavedObjectsRepository, +} from '@kbn/core-saved-objects-api-server'; import { PointInTimeFinder } from './point_in_time_finder'; const createPointInTimeFinderMock = ({ diff --git a/src/core/server/saved_objects/service/lib/point_in_time_finder.test.ts b/src/core/server/saved_objects/service/lib/point_in_time_finder.test.ts index f9d5098b5d896..29fe08e48b16d 100644 --- a/src/core/server/saved_objects/service/lib/point_in_time_finder.test.ts +++ b/src/core/server/saved_objects/service/lib/point_in_time_finder.test.ts @@ -7,13 +7,13 @@ */ import { loggerMock, MockedLogger } from '@kbn/logging-mocks'; -import type { SavedObjectsFindResult } from '..'; +import type { + SavedObjectsFindResult, + SavedObjectsCreatePointInTimeFinderOptions, +} from '@kbn/core-saved-objects-api-server'; import { savedObjectsRepositoryMock } from './repository.mock'; -import { - PointInTimeFinder, - SavedObjectsCreatePointInTimeFinderOptions, -} from './point_in_time_finder'; +import { PointInTimeFinder } from './point_in_time_finder'; const mockHits = [ { diff --git a/src/core/server/saved_objects/service/lib/repository.mock.ts b/src/core/server/saved_objects/service/lib/repository.mock.ts index 9c9b71d42e45e..d950b041d2432 100644 --- a/src/core/server/saved_objects/service/lib/repository.mock.ts +++ b/src/core/server/saved_objects/service/lib/repository.mock.ts @@ -7,7 +7,7 @@ */ import { savedObjectsPointInTimeFinderMock } from './point_in_time_finder.mock'; -import { ISavedObjectsRepository } from './repository'; +import type { ISavedObjectsRepository } from '@kbn/core-saved-objects-api-server'; const create = () => { const mock: jest.Mocked = { diff --git a/src/core/server/saved_objects/service/lib/repository.test.ts b/src/core/server/saved_objects/service/lib/repository.test.ts index f4015968597cd..28462feeb9f6b 100644 --- a/src/core/server/saved_objects/service/lib/repository.test.ts +++ b/src/core/server/saved_objects/service/lib/repository.test.ts @@ -24,20 +24,33 @@ import type { Payload } from '@hapi/boom'; import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { schema } from '@kbn/config-schema'; import type { SavedObject, SavedObjectReference } from '@kbn/core-saved-objects-common'; -import { SavedObjectsType, SavedObjectsBaseOptions, SavedObjectsFindOptions } from '../../types'; -import type { SavedObjectsUpdateObjectsSpacesResponse } from './update_objects_spaces'; -import { +import type { + SavedObjectsBaseOptions, + SavedObjectsFindOptions, + SavedObjectsUpdateObjectsSpacesResponse, SavedObjectsDeleteByNamespaceOptions, SavedObjectsIncrementCounterField, SavedObjectsIncrementCounterOptions, - SavedObjectsRepository, -} from './repository'; -import { SavedObjectsErrorHelpers } from './errors'; -import { - PointInTimeFinder, SavedObjectsCreatePointInTimeFinderDependencies, SavedObjectsCreatePointInTimeFinderOptions, -} from './point_in_time_finder'; + SavedObjectsBulkCreateObject, + SavedObjectsBulkGetObject, + SavedObjectsBulkUpdateObject, + SavedObjectsBulkUpdateOptions, + SavedObjectsCreateOptions, + SavedObjectsDeleteOptions, + SavedObjectsOpenPointInTimeOptions, + SavedObjectsResolveResponse, + SavedObjectsUpdateOptions, + SavedObjectsCollectMultiNamespaceReferencesObject, + SavedObjectsCollectMultiNamespaceReferencesResponse, + SavedObjectsUpdateObjectsSpacesObject, + SavedObjectsUpdateObjectsSpacesOptions, +} from '@kbn/core-saved-objects-api-server'; +import { SavedObjectsType } from '../../types'; +import { SavedObjectsRepository } from './repository'; +import { SavedObjectsErrorHelpers } from './errors'; +import { PointInTimeFinder } from './point_in_time_finder'; import { ALL_NAMESPACES_STRING } from './utils'; import { loggerMock } from '@kbn/logging-mocks'; import { @@ -54,24 +67,7 @@ import { LEGACY_URL_ALIAS_TYPE } from '../../object_types'; import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import * as esKuery from '@kbn/es-query'; import { errors as EsErrors } from '@elastic/elasticsearch'; -import { - SavedObjectsBulkCreateObject, - SavedObjectsBulkGetObject, - SavedObjectsBulkUpdateObject, - SavedObjectsBulkUpdateOptions, - SavedObjectsCreateOptions, - SavedObjectsDeleteOptions, - SavedObjectsOpenPointInTimeOptions, - SavedObjectsResolveResponse, - SavedObjectsUpdateOptions, -} from '../saved_objects_client'; import { SavedObjectsMappingProperties, SavedObjectsTypeMappingDefinition } from '../../mappings'; -import { - SavedObjectsCollectMultiNamespaceReferencesObject, - SavedObjectsCollectMultiNamespaceReferencesResponse, - SavedObjectsUpdateObjectsSpacesObject, - SavedObjectsUpdateObjectsSpacesOptions, -} from '../../..'; import { InternalBulkResolveError } from './internal_bulk_resolve'; const { nodeTypes } = esKuery; diff --git a/src/core/server/saved_objects/service/lib/search_dsl/pit_params.ts b/src/core/server/saved_objects/service/lib/search_dsl/pit_params.ts index 1a8dcb5cca2e9..c8be64e9a0494 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/pit_params.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/pit_params.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedObjectsPitParams } from '../../../types'; +import type { SavedObjectsPitParams } from '@kbn/core-saved-objects-api-server'; export function getPitParams(pit: SavedObjectsPitParams) { return { diff --git a/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts index 5fbb9aba04583..23aa6e1fbeebb 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts @@ -9,8 +9,8 @@ import Boom from '@hapi/boom'; import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; +import type { SavedObjectsPitParams } from '@kbn/core-saved-objects-api-server'; import { IndexMapping } from '../../../mappings'; -import { SavedObjectsPitParams } from '../../../types'; import { getQueryParams, HasReferenceQueryParams, SearchOperator } from './query_params'; import { getPitParams } from './pit_params'; import { getSortingParams } from './sorting_params'; diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts index 194caef879fe8..dfd1600e6d218 100644 --- a/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts +++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts @@ -16,12 +16,10 @@ import { import { elasticsearchClientMock } from '@kbn/core-elasticsearch-client-server-mocks'; import { loggerMock } from '@kbn/logging-mocks'; +import type { SavedObjectsUpdateObjectsSpacesObject } from '@kbn/core-saved-objects-api-server'; import { typeRegistryMock } from '../../saved_objects_type_registry.mock'; import { SavedObjectsSerializer } from '../../serialization'; -import type { - SavedObjectsUpdateObjectsSpacesObject, - UpdateObjectsSpacesParams, -} from './update_objects_spaces'; +import type { UpdateObjectsSpacesParams } from './update_objects_spaces'; import { updateObjectsSpaces } from './update_objects_spaces'; import { ALL_NAMESPACES_STRING } from './utils'; import { SavedObjectsErrorHelpers } from './errors'; diff --git a/src/core/server/saved_objects/service/lib/utils.test.ts b/src/core/server/saved_objects/service/lib/utils.test.ts index 0f502d8bfb9f1..8c836afd087d3 100644 --- a/src/core/server/saved_objects/service/lib/utils.test.ts +++ b/src/core/server/saved_objects/service/lib/utils.test.ts @@ -8,7 +8,7 @@ import { mockUuidv1, mockUuidv5 } from './utils.test.mock'; -import { SavedObjectsFindOptions } from '../../types'; +import { SavedObjectsFindOptions } from '@kbn/core-saved-objects-api-server'; import { SavedObjectsUtils } from './utils'; describe('SavedObjectsUtils', () => { diff --git a/src/core/server/saved_objects/service/lib/utils.ts b/src/core/server/saved_objects/service/lib/utils.ts index df79eba56d130..46f562d17aec3 100644 --- a/src/core/server/saved_objects/service/lib/utils.ts +++ b/src/core/server/saved_objects/service/lib/utils.ts @@ -8,8 +8,10 @@ import uuidv1 from 'uuid/v1'; import uuidv5 from 'uuid/v5'; -import { SavedObjectsFindOptions } from '../../types'; -import { SavedObjectsFindResponse } from '..'; +import type { + SavedObjectsFindOptions, + SavedObjectsFindResponse, +} from '@kbn/core-saved-objects-api-server'; export const DEFAULT_NAMESPACE_STRING = 'default'; export const ALL_NAMESPACES_STRING = '*'; diff --git a/src/core/server/saved_objects/service/saved_objects_client.test.ts b/src/core/server/saved_objects/service/saved_objects_client.test.ts index 7017d0d854b6f..77afd3f771a12 100644 --- a/src/core/server/saved_objects/service/saved_objects_client.test.ts +++ b/src/core/server/saved_objects/service/saved_objects_client.test.ts @@ -6,21 +6,16 @@ * Side Public License, v 1. */ -import { +import type { SavedObjectsBulkCreateObject, SavedObjectsBulkGetObject, SavedObjectsBulkResolveObject, SavedObjectsCheckConflictsObject, - SavedObjectsClient, SavedObjectsClosePointInTimeOptions, SavedObjectsCreateOptions, SavedObjectsDeleteOptions, SavedObjectsOpenPointInTimeOptions, SavedObjectsUpdateOptions, -} from './saved_objects_client'; -import { savedObjectsRepositoryMock } from './lib/repository.mock'; -import { savedObjectsClientMock } from './saved_objects_client.mock'; -import { SavedObjectsBaseOptions, SavedObjectsCollectMultiNamespaceReferencesObject, SavedObjectsCollectMultiNamespaceReferencesOptions, @@ -28,7 +23,10 @@ import { SavedObjectsFindOptions, SavedObjectsUpdateObjectsSpacesObject, SavedObjectsUpdateObjectsSpacesOptions, -} from '../..'; +} from '@kbn/core-saved-objects-api-server'; +import { SavedObjectsClient } from './saved_objects_client'; +import { savedObjectsRepositoryMock } from './lib/repository.mock'; +import { savedObjectsClientMock } from './saved_objects_client.mock'; describe('', () => { let mockRepository: ReturnType; diff --git a/src/core/server/saved_objects/types.ts b/src/core/server/saved_objects/types.ts index 175ab00c2757b..75f3abdc9f9fe 100644 --- a/src/core/server/saved_objects/types.ts +++ b/src/core/server/saved_objects/types.ts @@ -28,7 +28,7 @@ export interface SavedObjectStatusMeta { }; } -export type { SavedObjectsClientContract } from '@kbn/core-saved-objects-common'; +export type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; /** * @public diff --git a/src/core/server/ui_settings/create_or_upgrade_saved_config/get_upgradeable_config.test.ts b/src/core/server/ui_settings/create_or_upgrade_saved_config/get_upgradeable_config.test.ts index 34ef0c5b4f2e1..b3f7b9f2fd55a 100644 --- a/src/core/server/ui_settings/create_or_upgrade_saved_config/get_upgradeable_config.test.ts +++ b/src/core/server/ui_settings/create_or_upgrade_saved_config/get_upgradeable_config.test.ts @@ -6,9 +6,9 @@ * Side Public License, v 1. */ +import type { SavedObjectsFindResponse } from '@kbn/core-saved-objects-api-server'; import { getUpgradeableConfig } from './get_upgradeable_config'; import { savedObjectsClientMock } from '../../saved_objects/service/saved_objects_client.mock'; -import { SavedObjectsFindResponse } from '../../saved_objects'; describe('getUpgradeableConfig', () => { it('finds saved objects with type "config"', async () => { From f77ed4d56f003f0a4423102565c23c34327dcc5f Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 11:38:06 +0200 Subject: [PATCH 16/46] prepare the browser-side client --- .../core-saved-objects-common/src/index.ts | 2 ++ .../core-saved-objects-common/src/types.ts | 17 ++++++++++++++++ src/core/public/index.ts | 1 + .../saved_objects/saved_objects_client.ts | 20 ++++++++----------- 4 files changed, 28 insertions(+), 12 deletions(-) create mode 100644 packages/core/saved-objects/core-saved-objects-common/src/types.ts diff --git a/packages/core/saved-objects/core-saved-objects-common/src/index.ts b/packages/core/saved-objects/core-saved-objects-common/src/index.ts index 0210b5482e8e0..a04646e401b9b 100644 --- a/packages/core/saved-objects/core-saved-objects-common/src/index.ts +++ b/packages/core/saved-objects/core-saved-objects-common/src/index.ts @@ -31,3 +31,5 @@ export type { SavedObjectsImportActionRequiredWarning, SavedObjectsImportConflictError, } from './saved_objects_imports'; + +export type { SavedObjectTypeIdTuple } from './types'; diff --git a/packages/core/saved-objects/core-saved-objects-common/src/types.ts b/packages/core/saved-objects/core-saved-objects-common/src/types.ts new file mode 100644 index 0000000000000..78992162fc610 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-common/src/types.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +/** + * @public + */ +export interface SavedObjectTypeIdTuple { + /** The id of the saved object */ + id: string; + /** The type of the saved object */ + type: string; +} diff --git a/src/core/public/index.ts b/src/core/public/index.ts index 68da5ad6b5f14..eee64ef90fd11 100644 --- a/src/core/public/index.ts +++ b/src/core/public/index.ts @@ -151,6 +151,7 @@ export type { } from './saved_objects'; export type { SavedObject, + SavedObjectTypeIdTuple, SavedObjectAttribute, SavedObjectAttributes, SavedObjectAttributeSingle, diff --git a/src/core/public/saved_objects/saved_objects_client.ts b/src/core/public/saved_objects/saved_objects_client.ts index 413eeaa67db3e..c82ff38019641 100644 --- a/src/core/public/saved_objects/saved_objects_client.ts +++ b/src/core/public/saved_objects/saved_objects_client.ts @@ -10,6 +10,7 @@ import { pick, throttle, cloneDeep } from 'lodash'; import type { HttpSetup, HttpFetchOptions } from '@kbn/core-http-browser'; import type { SavedObject, + SavedObjectTypeIdTuple, SavedObjectReference, SavedObjectsMigrationVersion, } from '@kbn/core-saved-objects-common'; @@ -215,7 +216,7 @@ export interface SavedObjectsClientContract { * ]) */ bulkGet( - objects: Array<{ id: string; type: string }> + objects: SavedObjectTypeIdTuple[], ): Promise>; /** @@ -249,7 +250,7 @@ export interface SavedObjectsClientContract { * public client uses `bulkResolve` under the hood, so it behaves the same way. */ bulkResolve( - objects: Array<{ id: string; type: string }> + objects: SavedObjectTypeIdTuple[], ): Promise>; /** @@ -281,13 +282,8 @@ export interface SavedObjectsClientContract { ): Promise>; } -interface ObjectTypeAndId { - id: string; - type: string; -} - -const getObjectsToFetch = (queue: BatchGetQueueEntry[]): ObjectTypeAndId[] => { - const objects: ObjectTypeAndId[] = []; +const getObjectsToFetch = (queue: BatchGetQueueEntry[]): SavedObjectTypeIdTuple[] => { + const objects: SavedObjectTypeIdTuple[] = []; const inserted = new Set(); queue.forEach(({ id, type }) => { if (!inserted.has(`${type}|${id}`)) { @@ -300,7 +296,7 @@ const getObjectsToFetch = (queue: BatchGetQueueEntry[]): ObjectTypeAndId[] => { const getObjectsToResolve = (queue: BatchResolveQueueEntry[]) => { const responseIndices: number[] = []; - const objectsToResolve: ObjectTypeAndId[] = []; + const objectsToResolve: SavedObjectTypeIdTuple[] = []; const inserted = new Map(); queue.forEach(({ id, type }) => { const key = `${type}|${id}`; @@ -559,7 +555,7 @@ export class SavedObjectsClient implements SavedObjectsClientContract { }); }; - private async performBulkGet(objects: ObjectTypeAndId[]) { + private async performBulkGet(objects: SavedObjectTypeIdTuple[]) { const path = this.getPath(['_bulk_get']); const request: ReturnType = this.savedObjectsFetch(path, { method: 'POST', @@ -592,7 +588,7 @@ export class SavedObjectsClient implements SavedObjectsClientContract { }; }; - private async performBulkResolve(objects: ObjectTypeAndId[]) { + private async performBulkResolve(objects: SavedObjectTypeIdTuple[]) { const path = this.getPath(['_bulk_resolve']); const request: Promise> = this.savedObjectsFetch( path, From a769255fc45665047e1c4ab8ae395adccfaed774 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 11:41:07 +0200 Subject: [PATCH 17/46] fix one more usage --- src/core/server/ui_settings/ui_settings_client.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/core/server/ui_settings/ui_settings_client.ts b/src/core/server/ui_settings/ui_settings_client.ts index c6881d2817404..440072c0a769d 100644 --- a/src/core/server/ui_settings/ui_settings_client.ts +++ b/src/core/server/ui_settings/ui_settings_client.ts @@ -192,8 +192,7 @@ export class UiSettingsClient extends BaseUiSettingsClient { } private isIgnorableError(error: Error) { - const { isForbiddenError, isEsUnavailableError } = this.savedObjectsClient.errors; - + const { isForbiddenError, isEsUnavailableError } = SavedObjectsErrorHelpers; return isForbiddenError(error) || isEsUnavailableError(error); } } From 80d2ba3622bff89cfdf01481b55b81daae78031a Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 11:54:50 +0200 Subject: [PATCH 18/46] fix external usage --- .../server/saved_objects/spaces_saved_objects_client.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/spaces/server/saved_objects/spaces_saved_objects_client.ts b/x-pack/plugins/spaces/server/saved_objects/spaces_saved_objects_client.ts index 630a1baf2ef95..a7ef2dae5b386 100644 --- a/x-pack/plugins/spaces/server/saved_objects/spaces_saved_objects_client.ts +++ b/x-pack/plugins/spaces/server/saved_objects/spaces_saved_objects_client.ts @@ -78,7 +78,7 @@ export class SpacesSavedObjectsClient implements SavedObjectsClientContract { private readonly spaceId: string; private readonly types: string[]; private readonly spacesClient: ISpacesClient; - public readonly errors: SavedObjectsClientContract['errors']; + public readonly errors: typeof SavedObjectsErrorHelpers; constructor(options: SpacesSavedObjectsClientOptions) { const { baseClient, request, getSpacesService, typeRegistry } = options; @@ -90,7 +90,7 @@ export class SpacesSavedObjectsClient implements SavedObjectsClientContract { this.spacesClient = spacesService.createSpacesClient(request); this.spaceId = spacesService.getSpaceId(request); this.types = typeRegistry.getAllTypes().map((t) => t.name); - this.errors = baseClient.errors; + this.errors = SavedObjectsErrorHelpers; } async checkConflicts( From c39687a7d80cb6e9d2325dcafb9d7b606ff86d81 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 12:14:54 +0200 Subject: [PATCH 19/46] fix more external usages --- .../server/saved_objects/ensure_authorized.test.ts | 4 ++-- .../security/server/saved_objects/ensure_authorized.ts | 4 ++-- .../secure_saved_objects_client_wrapper.test.ts | 4 ++-- .../saved_objects/secure_saved_objects_client_wrapper.ts | 4 ++-- .../server/spaces/secure_spaces_client_wrapper.test.ts | 8 ++------ 5 files changed, 10 insertions(+), 14 deletions(-) diff --git a/x-pack/plugins/security/server/saved_objects/ensure_authorized.test.ts b/x-pack/plugins/security/server/saved_objects/ensure_authorized.test.ts index a5a6529d9d850..ea709aa475f2b 100644 --- a/x-pack/plugins/security/server/saved_objects/ensure_authorized.test.ts +++ b/x-pack/plugins/security/server/saved_objects/ensure_authorized.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { SavedObjectsClientContract } from '@kbn/core/server'; +import type { SavedObjectsErrorHelpers } from '@kbn/core/server'; import type { CheckSavedObjectsPrivileges } from '../authorization'; import { Actions } from '../authorization'; @@ -26,7 +26,7 @@ describe('ensureAuthorized', () => { const errors = { decorateForbiddenError: jest.fn().mockImplementation((err) => err), decorateGeneralError: jest.fn().mockImplementation((err) => err), - } as unknown as jest.Mocked; + } as unknown as jest.Mocked; const checkSavedObjectsPrivilegesAsCurrentUser: jest.MockedFunction = jest.fn(); return { actions, errors, checkSavedObjectsPrivilegesAsCurrentUser }; diff --git a/x-pack/plugins/security/server/saved_objects/ensure_authorized.ts b/x-pack/plugins/security/server/saved_objects/ensure_authorized.ts index f7005c1d4f86e..e945848d71105 100644 --- a/x-pack/plugins/security/server/saved_objects/ensure_authorized.ts +++ b/x-pack/plugins/security/server/saved_objects/ensure_authorized.ts @@ -5,14 +5,14 @@ * 2.0. */ -import type { SavedObjectsClientContract } from '@kbn/core/server'; +import type { SavedObjectsErrorHelpers } from '@kbn/core/server'; import type { Actions, CheckSavedObjectsPrivileges } from '../authorization'; import type { CheckPrivilegesResponse } from '../authorization/types'; export interface EnsureAuthorizedDependencies { actions: Actions; - errors: SavedObjectsClientContract['errors']; + errors: typeof SavedObjectsErrorHelpers; checkSavedObjectsPrivilegesAsCurrentUser: CheckSavedObjectsPrivileges; } diff --git a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts index 0f96beb4b5eaf..96505d2b5f963 100644 --- a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts +++ b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts @@ -11,7 +11,7 @@ import type { EcsEventOutcome, SavedObject, SavedObjectReferenceWithContext, - SavedObjectsClientContract, + SavedObjectsErrorHelpers, SavedObjectsResolveResponse, SavedObjectsUpdateObjectsSpacesResponseObject, } from '@kbn/core/server'; @@ -54,7 +54,7 @@ const createSecureSavedObjectsClientWrapperOptions = () => { decorateGeneralError: jest.fn().mockReturnValue(generalError), createBadRequestError: jest.fn().mockImplementation((message) => new Error(message)), isNotFoundError: jest.fn().mockReturnValue(false), - } as unknown as jest.Mocked; + } as unknown as jest.Mocked; const getSpacesService = jest.fn().mockReturnValue({ namespaceToSpaceId: (namespace?: string) => (namespace ? namespace : 'default'), }); diff --git a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts index 6b4c3bf4e799c..db0645992b2f7 100644 --- a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts +++ b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts @@ -51,7 +51,7 @@ interface SecureSavedObjectsClientWrapperOptions { actions: Actions; auditLogger: AuditLogger; baseClient: SavedObjectsClientContract; - errors: SavedObjectsClientContract['errors']; + errors: typeof SavedObjectsErrorHelpers; checkSavedObjectsPrivilegesAsCurrentUser: CheckSavedObjectsPrivileges; getSpacesService(): SpacesService | undefined; } @@ -86,7 +86,7 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra private readonly baseClient: SavedObjectsClientContract; private readonly checkSavedObjectsPrivilegesAsCurrentUser: CheckSavedObjectsPrivileges; private getSpacesService: () => SpacesService | undefined; - public readonly errors: SavedObjectsClientContract['errors']; + public readonly errors: typeof SavedObjectsErrorHelpers; constructor({ actions, diff --git a/x-pack/plugins/security/server/spaces/secure_spaces_client_wrapper.test.ts b/x-pack/plugins/security/server/spaces/secure_spaces_client_wrapper.test.ts index e0e0a925c8b27..2b65eff88d36f 100644 --- a/x-pack/plugins/security/server/spaces/secure_spaces_client_wrapper.test.ts +++ b/x-pack/plugins/security/server/spaces/secure_spaces_client_wrapper.test.ts @@ -7,11 +7,7 @@ import { mockEnsureAuthorized } from './secure_spaces_client_wrapper.test.mocks'; -import type { - EcsEventOutcome, - SavedObjectsClientContract, - SavedObjectsFindResponse, -} from '@kbn/core/server'; +import type { EcsEventOutcome, SavedObjectsFindResponse } from '@kbn/core/server'; import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import { httpServerMock } from '@kbn/core/server/mocks'; import type { GetAllSpacesPurpose, LegacyUrlAliasTarget, Space } from '@kbn/spaces-plugin/server'; @@ -106,7 +102,7 @@ const setup = ({ securityEnabled = false }: Opts = {}) => { const errors = { decorateForbiddenError: jest.fn().mockReturnValue(forbiddenError), // other errors exist but are not needed for these test cases - } as unknown as jest.Mocked; + } as unknown as jest.Mocked; const wrapper = new SecureSpacesClientWrapper( baseClient, From 7eaf4a71757b739c7d65ede80314b838386a3b69 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 12:46:35 +0200 Subject: [PATCH 20/46] one more --- .../security/server/spaces/secure_spaces_client_wrapper.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/security/server/spaces/secure_spaces_client_wrapper.ts b/x-pack/plugins/security/server/spaces/secure_spaces_client_wrapper.ts index 37de2293785a3..c33686a0f8cfa 100644 --- a/x-pack/plugins/security/server/spaces/secure_spaces_client_wrapper.ts +++ b/x-pack/plugins/security/server/spaces/secure_spaces_client_wrapper.ts @@ -7,7 +7,7 @@ import Boom from '@hapi/boom'; -import type { KibanaRequest, SavedObjectsClientContract } from '@kbn/core/server'; +import type { KibanaRequest, SavedObjectsErrorHelpers } from '@kbn/core/server'; import type { GetAllSpacesOptions, GetAllSpacesPurpose, @@ -52,7 +52,7 @@ export class SecureSpacesClientWrapper implements ISpacesClient { private readonly request: KibanaRequest, private readonly authorization: AuthorizationServiceSetup, private readonly auditLogger: AuditLogger, - private readonly errors: SavedObjectsClientContract['errors'] + private readonly errors: typeof SavedObjectsErrorHelpers ) { this.useRbac = this.authorization.mode.useRbacForRequest(this.request); } From 8ed9e5bd323c68c557ad0492197ddc61e9637a11 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 13:25:39 +0200 Subject: [PATCH 21/46] Create @kbn/core-saved-objects-api-browser package --- package.json | 2 + packages/BUILD.bazel | 2 + .../BUILD.bazel | 108 ++++++++ .../core-saved-objects-api-browser/README.md | 3 + .../jest.config.js | 13 + .../package.json | 8 + .../src/apis/base.ts | 14 + .../src/apis/bulk_create.ts | 26 ++ .../src/apis/bulk_resolve.ts | 14 + .../src/apis/bulk_update.ts | 23 ++ .../src/apis/create.ts | 27 ++ .../src/apis/delete.ts | 13 + .../src/apis/find.ts | 31 +++ .../src/apis/index.ts | 17 ++ .../src/apis/resolve.ts | 4 +- .../src/apis/update.ts | 16 ++ .../src/index.ts | 24 ++ .../src/saved_objects_client.ts | 157 +++++++++++ .../src/simple_saved_object.ts | 45 +++ .../tsconfig.json | 18 ++ src/core/public/index.ts | 28 +- src/core/public/saved_objects/index.ts | 26 +- .../saved_objects/saved_objects_client.ts | 257 ++---------------- .../saved_objects/simple_saved_object.ts | 22 +- yarn.lock | 8 + 25 files changed, 612 insertions(+), 294 deletions(-) create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/BUILD.bazel create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/README.md create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/jest.config.js create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/package.json create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/src/apis/base.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/src/apis/bulk_create.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/src/apis/bulk_resolve.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/src/apis/bulk_update.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/src/apis/create.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/src/apis/delete.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/src/apis/find.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/src/apis/index.ts rename src/core/public/saved_objects/types.ts => packages/core/saved-objects/core-saved-objects-api-browser/src/apis/resolve.ts (95%) create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/src/apis/update.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/src/index.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/src/saved_objects_client.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/src/simple_saved_object.ts create mode 100644 packages/core/saved-objects/core-saved-objects-api-browser/tsconfig.json diff --git a/package.json b/package.json index 3c45ff1ba6126..076b885a14b42 100644 --- a/package.json +++ b/package.json @@ -216,6 +216,7 @@ "@kbn/core-preboot-server": "link:bazel-bin/packages/core/preboot/core-preboot-server", "@kbn/core-preboot-server-internal": "link:bazel-bin/packages/core/preboot/core-preboot-server-internal", "@kbn/core-preboot-server-mocks": "link:bazel-bin/packages/core/preboot/core-preboot-server-mocks", + "@kbn/core-saved-objects-api-browser": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-browser", "@kbn/core-saved-objects-api-server": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-server", "@kbn/core-saved-objects-common": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-common", "@kbn/core-test-helpers-http-setup-browser": "link:bazel-bin/packages/core/test-helpers/core-test-helpers-http-setup-browser", @@ -813,6 +814,7 @@ "@types/kbn__core-preboot-server-internal": "link:bazel-bin/packages/core/preboot/core-preboot-server-internal/npm_module_types", "@types/kbn__core-preboot-server-mocks": "link:bazel-bin/packages/core/preboot/core-preboot-server-mocks/npm_module_types", "@types/kbn__core-public-internal-base": "link:bazel-bin/packages/core/public/internal-base/npm_module_types", + "@types/kbn__core-saved-objects-api-browser": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-browser/npm_module_types", "@types/kbn__core-saved-objects-api-server": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-server/npm_module_types", "@types/kbn__core-saved-objects-common": "link:bazel-bin/packages/core/saved-objects/core-saved-objects-common/npm_module_types", "@types/kbn__core-server-internal-base": "link:bazel-bin/packages/core/server/internal-base/npm_module_types", diff --git a/packages/BUILD.bazel b/packages/BUILD.bazel index 6d4f44f2f7e1a..bb723e4fac931 100644 --- a/packages/BUILD.bazel +++ b/packages/BUILD.bazel @@ -83,6 +83,7 @@ filegroup( "//packages/core/preboot/core-preboot-server-internal:build", "//packages/core/preboot/core-preboot-server-mocks:build", "//packages/core/preboot/core-preboot-server:build", + "//packages/core/saved-objects/core-saved-objects-api-browser:build", "//packages/core/saved-objects/core-saved-objects-api-server:build", "//packages/core/saved-objects/core-saved-objects-common:build", "//packages/core/test-helpers/core-test-helpers-http-setup-browser:build", @@ -301,6 +302,7 @@ filegroup( "//packages/core/preboot/core-preboot-server-internal:build_types", "//packages/core/preboot/core-preboot-server-mocks:build_types", "//packages/core/preboot/core-preboot-server:build_types", + "//packages/core/saved-objects/core-saved-objects-api-browser:build_types", "//packages/core/saved-objects/core-saved-objects-api-server:build_types", "//packages/core/saved-objects/core-saved-objects-common:build_types", "//packages/core/test-helpers/core-test-helpers-http-setup-browser:build_types", diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/BUILD.bazel b/packages/core/saved-objects/core-saved-objects-api-browser/BUILD.bazel new file mode 100644 index 0000000000000..57e9e94250cdc --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/BUILD.bazel @@ -0,0 +1,108 @@ +load("@npm//@bazel/typescript:index.bzl", "ts_config") +load("@build_bazel_rules_nodejs//:index.bzl", "js_library") +load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project") + +PKG_DIRNAME = "core-saved-objects-api-browser" +PKG_REQUIRE_NAME = "@kbn/core-saved-objects-api-browser" + +SOURCE_FILES = glob( + [ + "src/**/*.ts", + "src/**/*.tsx", + ], + exclude = [ + "**/*.test.*", + "**/*.stories.*", + ], +) + +SRCS = SOURCE_FILES + +filegroup( + name = "srcs", + srcs = SRCS, +) + +NPM_MODULE_EXTRA_FILES = [ + "package.json", +] + +RUNTIME_DEPS = [ + "@npm//react" +] + +TYPES_DEPS = [ + "@npm//@types/node", + "@npm//@types/jest", + "//packages/core/saved-objects/core-saved-objects-common:npm_module_types", + "//packages/core/saved-objects/core-saved-objects-api-server:npm_module_types", +] + +jsts_transpiler( + name = "target_node", + srcs = SRCS, + build_pkg_name = package_name(), +) + +jsts_transpiler( + name = "target_web", + srcs = SRCS, + build_pkg_name = package_name(), + web = True, +) + +ts_config( + name = "tsconfig", + src = "tsconfig.json", + deps = [ + "//:tsconfig.base.json", + "//:tsconfig.bazel.json", + ], +) + +ts_project( + name = "tsc_types", + args = ['--pretty'], + srcs = SRCS, + deps = TYPES_DEPS, + declaration = True, + declaration_map = True, + emit_declaration_only = True, + out_dir = "target_types", + root_dir = "src", + tsconfig = ":tsconfig", +) + +js_library( + name = PKG_DIRNAME, + srcs = NPM_MODULE_EXTRA_FILES, + deps = RUNTIME_DEPS + [":target_node", ":target_web"], + package_name = PKG_REQUIRE_NAME, + visibility = ["//visibility:public"], +) + +pkg_npm( + name = "npm_module", + deps = [":" + PKG_DIRNAME], +) + +filegroup( + name = "build", + srcs = [":npm_module"], + visibility = ["//visibility:public"], +) + +pkg_npm_types( + name = "npm_module_types", + srcs = SRCS, + deps = [":tsc_types"], + package_name = PKG_REQUIRE_NAME, + tsconfig = ":tsconfig", + visibility = ["//visibility:public"], +) + +filegroup( + name = "build_types", + srcs = [":npm_module_types"], + visibility = ["//visibility:public"], +) diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/README.md b/packages/core/saved-objects/core-saved-objects-api-browser/README.md new file mode 100644 index 0000000000000..9e6d2592ed72d --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/README.md @@ -0,0 +1,3 @@ +# @kbn/core-saved-objects-api-browser + +This package contains the public types for core's browser-side savedObjects client APIs. diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/jest.config.js b/packages/core/saved-objects/core-saved-objects-api-browser/jest.config.js new file mode 100644 index 0000000000000..4da6aa55e6c12 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/jest.config.js @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +module.exports = { + preset: '@kbn/test', + rootDir: '../../../..', + roots: ['/packages/core/saved-objects/core-saved-objects-api-browser'], +}; diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/package.json b/packages/core/saved-objects/core-saved-objects-api-browser/package.json new file mode 100644 index 0000000000000..7e40339fbf326 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/package.json @@ -0,0 +1,8 @@ +{ + "name": "@kbn/core-saved-objects-api-browser", + "private": true, + "version": "1.0.0", + "main": "./target_node/index.js", + "browser": "./target_web/index.js", + "license": "SSPL-1.0 OR Elastic License 2.0" +} diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/base.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/base.ts new file mode 100644 index 0000000000000..5a741d95c58b6 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/base.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { ISimpleSavedObject } from '../simple_saved_object'; + +/** @public */ +export interface SavedObjectsBatchResponse { + savedObjects: Array>; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/bulk_create.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/bulk_create.ts new file mode 100644 index 0000000000000..4e4190cb55675 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/bulk_create.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectsCreateOptions } from './create'; + +/** + * @param type - Create a SavedObject of the given type + * @param attributes - Create a SavedObject with the given attributes + * + * @public + */ +export interface SavedObjectsBulkCreateObject extends SavedObjectsCreateOptions { + type: string; + attributes: T; +} + +/** @public */ +export interface SavedObjectsBulkCreateOptions { + /** If a document with the given `id` already exists, overwrite it's contents (default=false). */ + overwrite?: boolean; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/bulk_resolve.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/bulk_resolve.ts new file mode 100644 index 0000000000000..58316983c7a8d --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/bulk_resolve.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { ResolvedSimpleSavedObject } from './resolve'; + +/** @public */ +export interface SavedObjectsBulkResolveResponse { + resolved_objects: Array>; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/bulk_update.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/bulk_update.ts new file mode 100644 index 0000000000000..f5ba2cc249c19 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/bulk_update.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectReference } from '@kbn/core-saved-objects-common'; + +/** @public */ +export interface SavedObjectsBulkUpdateObject { + type: string; + id: string; + attributes: T; + version?: string; + references?: SavedObjectReference[]; +} + +/** @public */ +export interface SavedObjectsBulkUpdateOptions { + namespace?: string; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/create.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/create.ts new file mode 100644 index 0000000000000..fb2e70d7d1ebd --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/create.ts @@ -0,0 +1,27 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { + SavedObjectReference, + SavedObjectsMigrationVersion, +} from '@kbn/core-saved-objects-common'; + +/** @public */ +export interface SavedObjectsCreateOptions { + /** + * (Not recommended) Specify an id instead of having the saved objects service generate one for you. + */ + id?: string; + /** If a document with the given `id` already exists, overwrite it's contents (default=false). */ + overwrite?: boolean; + /** {@inheritDoc SavedObjectsMigrationVersion} */ + migrationVersion?: SavedObjectsMigrationVersion; + /** A semver value that is used when upgrading objects between Kibana versions. */ + coreMigrationVersion?: string; + references?: SavedObjectReference[]; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/delete.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/delete.ts new file mode 100644 index 0000000000000..598a35a0aad41 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/delete.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +/** @public */ +export interface SavedObjectsDeleteOptions { + /** Force deletion of an object that exists in multiple namespaces */ + force?: boolean; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/find.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/find.ts new file mode 100644 index 0000000000000..61e11915b6348 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/find.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectsFindOptions as SavedObjectFindOptionsServer } from '@kbn/core-saved-objects-api-server'; +import type { SavedObjectsBatchResponse } from './base'; + +/** + * @public + */ +export type SavedObjectsFindOptions = Omit< + SavedObjectFindOptionsServer, + 'pit' | 'rootSearchFields' | 'searchAfter' | 'sortOrder' | 'typeToNamespacesMap' +>; + +/** + * Return type of the Saved Objects `find()` method. + * + * @public + */ +export interface SavedObjectsFindResponse + extends SavedObjectsBatchResponse { + aggregations?: A; + total: number; + perPage: number; + page: number; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/index.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/index.ts new file mode 100644 index 0000000000000..3c7a8748212f8 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export type { SavedObjectsBatchResponse } from './base'; +export type { SavedObjectsBulkCreateObject, SavedObjectsBulkCreateOptions } from './bulk_create'; +export type { SavedObjectsBulkResolveResponse } from './bulk_resolve'; +export type { SavedObjectsBulkUpdateObject, SavedObjectsBulkUpdateOptions } from './bulk_update'; +export type { SavedObjectsCreateOptions } from './create'; +export type { SavedObjectsDeleteOptions } from './delete'; +export type { SavedObjectsFindResponse, SavedObjectsFindOptions } from './find'; +export type { ResolvedSimpleSavedObject } from './resolve'; +export type { SavedObjectsUpdateOptions } from './update'; diff --git a/src/core/public/saved_objects/types.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/resolve.ts similarity index 95% rename from src/core/public/saved_objects/types.ts rename to packages/core/saved-objects/core-saved-objects-api-browser/src/apis/resolve.ts index 8a643fe4d299a..2436a34423f94 100644 --- a/src/core/public/saved_objects/types.ts +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/resolve.ts @@ -7,7 +7,7 @@ */ import type { SavedObjectsResolveResponse } from '@kbn/core-saved-objects-api-server'; -import { SimpleSavedObject } from './simple_saved_object'; +import { ISimpleSavedObject } from '../simple_saved_object'; /** * This interface is a very simple wrapper for SavedObjects resolved from the server @@ -19,7 +19,7 @@ export interface ResolvedSimpleSavedObject { /** * The saved object that was found. */ - saved_object: SimpleSavedObject; + saved_object: ISimpleSavedObject; /** * The outcome for a successful `resolve` call is one of the following values: * diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/update.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/update.ts new file mode 100644 index 0000000000000..dd9a6dc523229 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/update.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectReference } from '@kbn/core-saved-objects-common'; + +/** @public */ +export interface SavedObjectsUpdateOptions { + version?: string; + upsert?: Attributes; + references?: SavedObjectReference[]; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/index.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/index.ts new file mode 100644 index 0000000000000..336e25838ea92 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/index.ts @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +export type { SavedObjectsClientContract } from './saved_objects_client'; +export type { ISimpleSavedObject } from './simple_saved_object'; +export type { + SavedObjectsCreateOptions, + SavedObjectsDeleteOptions, + SavedObjectsBatchResponse, + SavedObjectsFindOptions, + SavedObjectsUpdateOptions, + ResolvedSimpleSavedObject, + SavedObjectsBulkUpdateObject, + SavedObjectsFindResponse, + SavedObjectsBulkCreateOptions, + SavedObjectsBulkUpdateOptions, + SavedObjectsBulkResolveResponse, + SavedObjectsBulkCreateObject, +} from './apis'; diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/saved_objects_client.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/saved_objects_client.ts new file mode 100644 index 0000000000000..5741e05ccddc1 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/saved_objects_client.ts @@ -0,0 +1,157 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObjectTypeIdTuple } from '@kbn/core-saved-objects-common'; +import type { + ResolvedSimpleSavedObject, + SavedObjectsBatchResponse, + SavedObjectsBulkCreateObject, + SavedObjectsBulkCreateOptions, + SavedObjectsBulkResolveResponse, + SavedObjectsBulkUpdateObject, + SavedObjectsCreateOptions, + SavedObjectsFindResponse, + SavedObjectsFindOptions, + SavedObjectsUpdateOptions, + SavedObjectsDeleteOptions, +} from './apis'; +import type { ISimpleSavedObject } from './simple_saved_object'; + +/** + * The client-side SavedObjectsClient is a thin convenience library around the SavedObjects + * HTTP API for interacting with Saved Objects. + * + * @public + */ +export interface SavedObjectsClientContract { + /** + * Persists an object + */ + create( + type: string, + attributes: T, + options?: SavedObjectsCreateOptions + ): Promise>; + + /** + * Creates multiple documents at once + * @returns The result of the create operation containing created saved objects. + */ + bulkCreate( + objects: SavedObjectsBulkCreateObject[], + options?: SavedObjectsBulkCreateOptions + ): Promise>; + + /** + * Deletes an object + */ + delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>; + + /** + * Search for objects + * + * @param {object} [options={}] + * @property {string} options.type + * @property {string} options.search + * @property {string} options.searchFields - see Elasticsearch Simple Query String + * Query field argument for more information + * @property {integer} [options.page=1] + * @property {integer} [options.perPage=20] + * @property {array} options.fields + * @property {object} [options.hasReference] - { type, id } + * @returns A find result with objects matching the specified search. + */ + find( + options: SavedObjectsFindOptions + ): Promise>; + + /** + * Fetches a single object + * + * @param {string} type + * @param {string} id + * @returns The saved object for the given type and id. + */ + get(type: string, id: string): Promise>; + + /** + * Returns an array of objects by id + * + * @param {array} objects - an array ids, or an array of objects containing id and optionally type + * @returns The saved objects with the given type and ids requested + * @example + * + * bulkGet([ + * { id: 'one', type: 'config' }, + * { id: 'foo', type: 'index-pattern' } + * ]) + */ + bulkGet(objects: SavedObjectTypeIdTuple[]): Promise>; + + /** + * Resolves a single object + * + * @param {string} type + * @param {string} id + * @returns The resolve result for the saved object for the given type and id. + * + * @note Saved objects that Kibana fails to find are replaced with an error object and an "exactMatch" outcome. The rationale behind the + * outcome is that "exactMatch" is the default outcome, and the outcome only changes if an alias is found. This behavior for the `resolve` + * API is unique to the public client, which batches individual calls with `bulkResolve` under the hood. We don't throw an error in that + * case for legacy compatibility reasons. + */ + resolve(type: string, id: string): Promise>; + + /** + * Resolves an array of objects by id, using any legacy URL aliases if they exist + * + * @param objects - an array of objects containing id, type + * @returns The bulk resolve result for the saved objects for the given types and ids. + * @example + * + * bulkResolve([ + * { id: 'one', type: 'config' }, + * { id: 'foo', type: 'index-pattern' } + * ]) + * + * @note Saved objects that Kibana fails to find are replaced with an error object and an "exactMatch" outcome. The rationale behind the + * outcome is that "exactMatch" is the default outcome, and the outcome only changes if an alias is found. The `resolve` method in the + * public client uses `bulkResolve` under the hood, so it behaves the same way. + */ + bulkResolve( + objects: SavedObjectTypeIdTuple[] + ): Promise>; + + /** + * Updates an object + * + * @param {string} type + * @param {string} id + * @param {object} attributes + * @param {object} options + * @prop {integer} options.version - ensures version matches that of persisted object + * @prop {object} options.migrationVersion - The optional migrationVersion of this document + * @returns + */ + update( + type: string, + id: string, + attributes: T, + options?: SavedObjectsUpdateOptions + ): Promise>; + + /** + * Update multiple documents at once + * + * @param {array} objects - [{ type, id, attributes, options: { version, references } }] + * @returns The result of the update operation containing both failed and updated saved objects. + */ + bulkUpdate( + objects: SavedObjectsBulkUpdateObject[] + ): Promise>; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/simple_saved_object.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/simple_saved_object.ts new file mode 100644 index 0000000000000..ed4a602538544 --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/simple_saved_object.ts @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { SavedObject as SavedObjectType } from '@kbn/core-saved-objects-common'; + +/** + * Very simple wrapper for SavedObjects loaded from the server + * with the {@link SavedObjectsClientContract}. + * + * It provides basic functionality for creating/saving/deleting saved objects, + * but doesn't include any type-specific implementations. + * + * @public + */ +export interface ISimpleSavedObject { + attributes: T; + _version?: SavedObjectType['version']; + id: SavedObjectType['id']; + type: SavedObjectType['type']; + migrationVersion: SavedObjectType['migrationVersion']; + coreMigrationVersion: SavedObjectType['coreMigrationVersion']; + error: SavedObjectType['error']; + references: SavedObjectType['references']; + updatedAt: SavedObjectType['updated_at']; + /** + * Space(s) that this saved object exists in. This attribute is not used for "global" saved object types which are registered with + * `namespaceType: 'agnostic'`. + */ + namespaces: SavedObjectType['namespaces']; + + get(key: string): any; + + set(key: string, value: any): T; + + has(key: string): boolean; + + save(): Promise>; + + delete(): Promise<{}>; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/tsconfig.json b/packages/core/saved-objects/core-saved-objects-api-browser/tsconfig.json new file mode 100644 index 0000000000000..39d3c7097814a --- /dev/null +++ b/packages/core/saved-objects/core-saved-objects-api-browser/tsconfig.json @@ -0,0 +1,18 @@ +{ + "extends": "../../../../tsconfig.bazel.json", + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "emitDeclarationOnly": true, + "outDir": "target_types", + "rootDir": "src", + "stripInternal": false, + "types": [ + "jest", + "node" + ] + }, + "include": [ + "src/**/*" + ] +} diff --git a/src/core/public/index.ts b/src/core/public/index.ts index eee64ef90fd11..732186321e213 100644 --- a/src/core/public/index.ts +++ b/src/core/public/index.ts @@ -130,25 +130,21 @@ export type { // TODO: check if can be exported as type. export { SimpleSavedObject } from './saved_objects'; export type { - SavedObjectsBatchResponse, - SavedObjectsBulkCreateObject, - SavedObjectsBulkCreateOptions, - SavedObjectsBulkResolveObject, - SavedObjectsBulkResolveResponse, - SavedObjectsBulkUpdateObject, - SavedObjectsBulkUpdateOptions, + SavedObjectsClientContract, + ISimpleSavedObject, SavedObjectsCreateOptions, - SavedObjectsFindResponsePublic, - SavedObjectsResolveResponse, - SavedObjectsUpdateOptions, - SavedObjectsBaseOptions, + SavedObjectsDeleteOptions, + SavedObjectsBatchResponse, SavedObjectsFindOptions, - SavedObjectsFindOptionsReference, - SavedObjectsClientContract, - SavedObjectReferenceWithContext, - SavedObjectsCollectMultiNamespaceReferencesResponse, + SavedObjectsUpdateOptions, ResolvedSimpleSavedObject, -} from './saved_objects'; + SavedObjectsBulkUpdateObject, + SavedObjectsFindResponse, + SavedObjectsBulkCreateOptions, + SavedObjectsBulkUpdateOptions, + SavedObjectsBulkResolveResponse, + SavedObjectsBulkCreateObject, +} from '@kbn/core-saved-objects-api-browser'; export type { SavedObject, SavedObjectTypeIdTuple, diff --git a/src/core/public/saved_objects/index.ts b/src/core/public/saved_objects/index.ts index 76675d3707993..ae482df225a48 100644 --- a/src/core/public/saved_objects/index.ts +++ b/src/core/public/saved_objects/index.ts @@ -5,30 +5,8 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ -export { SavedObjectsService } from './saved_objects_service'; -export type { - SavedObjectsBatchResponse, - SavedObjectsBulkCreateObject, - SavedObjectsBulkCreateOptions, - SavedObjectsBulkUpdateObject, - SavedObjectsClient, - SavedObjectsClientContract, - SavedObjectsCreateOptions, - SavedObjectsFindResponsePublic, - SavedObjectsUpdateOptions, - SavedObjectsBulkUpdateOptions, - SavedObjectsBulkResolveResponse, -} from './saved_objects_client'; +export { SavedObjectsService } from './saved_objects_service'; +export type { SavedObjectsClient } from './saved_objects_client'; export { SimpleSavedObject } from './simple_saved_object'; -export type { ResolvedSimpleSavedObject } from './types'; export type { SavedObjectsStart } from './saved_objects_service'; -export type { - SavedObjectsBaseOptions, - SavedObjectsFindOptions, - SavedObjectsFindOptionsReference, - SavedObjectReferenceWithContext, - SavedObjectsCollectMultiNamespaceReferencesResponse, - SavedObjectsBulkResolveObject, - SavedObjectsResolveResponse, -} from '../../server'; diff --git a/src/core/public/saved_objects/saved_objects_client.ts b/src/core/public/saved_objects/saved_objects_client.ts index c82ff38019641..616daf0fc5c54 100644 --- a/src/core/public/saved_objects/saved_objects_client.ts +++ b/src/core/public/saved_objects/saved_objects_client.ts @@ -8,115 +8,32 @@ import { pick, throttle, cloneDeep } from 'lodash'; import type { HttpSetup, HttpFetchOptions } from '@kbn/core-http-browser'; -import type { - SavedObject, - SavedObjectTypeIdTuple, - SavedObjectReference, - SavedObjectsMigrationVersion, -} from '@kbn/core-saved-objects-common'; +import type { SavedObject, SavedObjectTypeIdTuple } from '@kbn/core-saved-objects-common'; import type { SavedObjectsBulkResolveResponse as SavedObjectsBulkResolveResponseServer, SavedObjectsClientContract as SavedObjectsApi, - SavedObjectsFindOptions as SavedObjectFindOptionsServer, + SavedObjectsFindResponse as SavedObjectsFindResponseServer, SavedObjectsResolveResponse, } from '@kbn/core-saved-objects-api-server'; +import type { + SavedObjectsClientContract, + SavedObjectsCreateOptions, + SavedObjectsDeleteOptions, + SavedObjectsBatchResponse, + SavedObjectsFindOptions, + SavedObjectsUpdateOptions, + ResolvedSimpleSavedObject, + SavedObjectsBulkUpdateObject, + SavedObjectsFindResponse, + SavedObjectsBulkCreateOptions, + SavedObjectsBulkCreateObject, +} from '@kbn/core-saved-objects-api-browser'; import { SimpleSavedObject } from './simple_saved_object'; -import type { ResolvedSimpleSavedObject } from './types'; type PromiseType> = T extends Promise ? U : never; -type SavedObjectsFindOptions = Omit< - SavedObjectFindOptionsServer, - 'pit' | 'rootSearchFields' | 'searchAfter' | 'sortOrder' | 'typeToNamespacesMap' ->; - -type SavedObjectsFindResponse = Omit>, 'pit_id'>; - -/** @public */ -export interface SavedObjectsCreateOptions { - /** - * (Not recommended) Specify an id instead of having the saved objects service generate one for you. - */ - id?: string; - /** If a document with the given `id` already exists, overwrite it's contents (default=false). */ - overwrite?: boolean; - /** {@inheritDoc SavedObjectsMigrationVersion} */ - migrationVersion?: SavedObjectsMigrationVersion; - /** A semver value that is used when upgrading objects between Kibana versions. */ - coreMigrationVersion?: string; - references?: SavedObjectReference[]; -} - -/** - * @param type - Create a SavedObject of the given type - * @param attributes - Create a SavedObject with the given attributes - * - * @public - */ -export interface SavedObjectsBulkCreateObject extends SavedObjectsCreateOptions { - type: string; - attributes: T; -} - -/** @public */ -export interface SavedObjectsBulkCreateOptions { - /** If a document with the given `id` already exists, overwrite it's contents (default=false). */ - overwrite?: boolean; -} - -/** @public */ -export interface SavedObjectsBulkUpdateObject { - type: string; - id: string; - attributes: T; - version?: string; - references?: SavedObjectReference[]; -} - -/** @public */ -export interface SavedObjectsBulkUpdateOptions { - namespace?: string; -} - -/** @public */ -export interface SavedObjectsUpdateOptions { - version?: string; - upsert?: Attributes; - references?: SavedObjectReference[]; -} - -/** @public */ -export interface SavedObjectsBatchResponse { - savedObjects: Array>; -} - -/** @public */ -export interface SavedObjectsDeleteOptions { - /** Force deletion of an object that exists in multiple namespaces */ - force?: boolean; -} - -/** @public */ -export interface SavedObjectsBulkResolveResponse { - resolved_objects: Array>; -} - -/** - * Return type of the Saved Objects `find()` method. - * - * *Note*: this type is different between the Public and Server Saved Objects - * clients. - * - * @public - */ -export interface SavedObjectsFindResponsePublic - extends SavedObjectsBatchResponse { - aggregations?: A; - total: number; - perPage: number; - page: number; -} +type SavedObjectsFindResponseInternal = Omit; interface BatchGetQueueEntry { type: string; @@ -146,142 +63,6 @@ const BATCH_INTERVAL = 100; const API_BASE_URL = '/api/saved_objects/'; -/** - * The client-side SavedObjectsClient is a thin convenience library around the SavedObjects - * HTTP API for interacting with Saved Objects. - * - * @public - */ -export interface SavedObjectsClientContract { - /** - * Persists an object - */ - create( - type: string, - attributes: T, - options?: SavedObjectsCreateOptions - ): Promise>; - - /** - * Creates multiple documents at once - * @returns The result of the create operation containing created saved objects. - */ - bulkCreate( - objects: SavedObjectsBulkCreateObject[], - options?: SavedObjectsBulkCreateOptions - ): Promise>; - - /** - * Deletes an object - */ - delete(type: string, id: string, options?: SavedObjectsDeleteOptions): Promise<{}>; - - /** - * Search for objects - * - * @param {object} [options={}] - * @property {string} options.type - * @property {string} options.search - * @property {string} options.searchFields - see Elasticsearch Simple Query String - * Query field argument for more information - * @property {integer} [options.page=1] - * @property {integer} [options.perPage=20] - * @property {array} options.fields - * @property {object} [options.hasReference] - { type, id } - * @returns A find result with objects matching the specified search. - */ - find( - options: SavedObjectsFindOptions - ): Promise>; - - /** - * Fetches a single object - * - * @param {string} type - * @param {string} id - * @returns The saved object for the given type and id. - */ - get(type: string, id: string): Promise>; - - /** - * Returns an array of objects by id - * - * @param {array} objects - an array ids, or an array of objects containing id and optionally type - * @returns The saved objects with the given type and ids requested - * @example - * - * bulkGet([ - * { id: 'one', type: 'config' }, - * { id: 'foo', type: 'index-pattern' } - * ]) - */ - bulkGet( - objects: SavedObjectTypeIdTuple[], - ): Promise>; - - /** - * Resolves a single object - * - * @param {string} type - * @param {string} id - * @returns The resolve result for the saved object for the given type and id. - * - * @note Saved objects that Kibana fails to find are replaced with an error object and an "exactMatch" outcome. The rationale behind the - * outcome is that "exactMatch" is the default outcome, and the outcome only changes if an alias is found. This behavior for the `resolve` - * API is unique to the public client, which batches individual calls with `bulkResolve` under the hood. We don't throw an error in that - * case for legacy compatibility reasons. - */ - resolve(type: string, id: string): Promise>; - - /** - * Resolves an array of objects by id, using any legacy URL aliases if they exist - * - * @param objects - an array of objects containing id, type - * @returns The bulk resolve result for the saved objects for the given types and ids. - * @example - * - * bulkResolve([ - * { id: 'one', type: 'config' }, - * { id: 'foo', type: 'index-pattern' } - * ]) - * - * @note Saved objects that Kibana fails to find are replaced with an error object and an "exactMatch" outcome. The rationale behind the - * outcome is that "exactMatch" is the default outcome, and the outcome only changes if an alias is found. The `resolve` method in the - * public client uses `bulkResolve` under the hood, so it behaves the same way. - */ - bulkResolve( - objects: SavedObjectTypeIdTuple[], - ): Promise>; - - /** - * Updates an object - * - * @param {string} type - * @param {string} id - * @param {object} attributes - * @param {object} options - * @prop {integer} options.version - ensures version matches that of persisted object - * @prop {object} options.migrationVersion - The optional migrationVersion of this document - * @returns - */ - update( - type: string, - id: string, - attributes: T, - options?: SavedObjectsUpdateOptions - ): Promise>; - - /** - * Update multiple documents at once - * - * @param {array} objects - [{ type, id, attributes, options: { version, references } }] - * @returns The result of the update operation containing both failed and updated saved objects. - */ - bulkUpdate( - objects: SavedObjectsBulkUpdateObject[] - ): Promise>; -} - const getObjectsToFetch = (queue: BatchGetQueueEntry[]): SavedObjectTypeIdTuple[] => { const objects: SavedObjectTypeIdTuple[] = []; const inserted = new Set(); @@ -475,7 +256,7 @@ export class SavedObjectsClient implements SavedObjectsClientContract { public find = ( options: SavedObjectsFindOptions - ): Promise> => { + ): Promise> => { const path = this.getPath(['_find']); const renameMap = { defaultSearchOperator: 'default_search_operator', @@ -517,7 +298,7 @@ export class SavedObjectsClient implements SavedObjectsClientContract { query, }); return request.then((resp) => { - return renameKeys( + return renameKeys( { aggregations: 'aggregations', saved_objects: 'savedObjects', @@ -529,7 +310,7 @@ export class SavedObjectsClient implements SavedObjectsClientContract { ...resp, saved_objects: resp.saved_objects.map((d) => this.createSavedObject(d)), } - ) as SavedObjectsFindResponsePublic; + ) as SavedObjectsFindResponse; }); }; diff --git a/src/core/public/saved_objects/simple_saved_object.ts b/src/core/public/saved_objects/simple_saved_object.ts index 4daae92867538..7caa83c2f784e 100644 --- a/src/core/public/saved_objects/simple_saved_object.ts +++ b/src/core/public/saved_objects/simple_saved_object.ts @@ -8,21 +8,19 @@ import { set } from '@elastic/safer-lodash-set'; import { get, has } from 'lodash'; -import { SavedObject as SavedObjectType } from '../../server'; -import { SavedObjectsClientContract } from './saved_objects_client'; +import type { SavedObject as SavedObjectType } from '@kbn/core-saved-objects-common'; +import type { + SavedObjectsClientContract, + ISimpleSavedObject, +} from '@kbn/core-saved-objects-api-browser'; /** - * This class is a very simple wrapper for SavedObjects loaded from the server - * with the {@link SavedObjectsClientContract}. - * - * It provides basic functionality for creating/saving/deleting saved objects, - * but doesn't include any type-specific implementations. + * Core internal implementation of {@link ISimpleSavedObject} * * @public */ -export class SimpleSavedObject { +export class SimpleSavedObject implements ISimpleSavedObject { public attributes: T; - // We want to use the same interface this class had in JS public _version?: SavedObjectType['version']; public id: SavedObjectType['id']; public type: SavedObjectType['type']; @@ -31,10 +29,6 @@ export class SimpleSavedObject { public error: SavedObjectType['error']; public references: SavedObjectType['references']; public updatedAt: SavedObjectType['updated_at']; - /** - * Space(s) that this saved object exists in. This attribute is not used for "global" saved object types which are registered with - * `namespaceType: 'agnostic'`. - */ public namespaces: SavedObjectType['namespaces']; constructor( @@ -78,7 +72,7 @@ export class SimpleSavedObject { return has(this.attributes, key); } - public save(): Promise> { + public save(): Promise> { if (this.id) { return this.client .update(this.type, this.id, this.attributes, { diff --git a/yarn.lock b/yarn.lock index 0fced9dff9676..62477ab650104 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3351,6 +3351,10 @@ version "0.0.0" uid "" +"@kbn/core-saved-objects-api-browser@link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-browser": + version "0.0.0" + uid "" + "@kbn/core-saved-objects-api-server@link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-server": version "0.0.0" uid "" @@ -7118,6 +7122,10 @@ version "0.0.0" uid "" +"@types/kbn__core-saved-objects-api-browser@link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-browser/npm_module_types": + version "0.0.0" + uid "" + "@types/kbn__core-saved-objects-api-server@link:bazel-bin/packages/core/saved-objects/core-saved-objects-api-server/npm_module_types": version "0.0.0" uid "" From b4289e056205a475805d8cdf4795632c1d11ccab Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 13:28:22 +0200 Subject: [PATCH 22/46] fix more usages of error helper --- .../saved_objects/encrypted_saved_objects_client_wrapper.ts | 4 ++-- .../server/services/exception_lists/create_endpoint_list.ts | 4 ++-- .../exception_lists/create_endpoint_trusted_apps_list.ts | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts index 84141db8967a7..0b9c81cc33334 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts @@ -34,7 +34,7 @@ import type { SavedObjectsUpdateOptions, SavedObjectsUpdateResponse, } from '@kbn/core/server'; -import { SavedObjectsUtils } from '@kbn/core/server'; +import { SavedObjectsErrorHelpers, SavedObjectsUtils } from '@kbn/core/server'; import type { AuthenticatedUser } from '@kbn/security-plugin/common/model'; import type { EncryptedSavedObjectsService } from '../crypto'; @@ -50,7 +50,7 @@ interface EncryptedSavedObjectsClientOptions { export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientContract { constructor( private readonly options: EncryptedSavedObjectsClientOptions, - public readonly errors = options.baseClient.errors + public readonly errors = SavedObjectsErrorHelpers ) {} public async checkConflicts( diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts b/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts index d197aed76a8b6..ac08f8a19aedb 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { SavedObjectsClientContract } from '@kbn/core/server'; +import { SavedObjectsClientContract, SavedObjectsErrorHelpers } from '@kbn/core/server'; import uuid from 'uuid'; import { Version } from '@kbn/securitysolution-io-ts-types'; import type { ExceptionListSchema } from '@kbn/securitysolution-io-ts-list-types'; @@ -64,7 +64,7 @@ export const createEndpointList = async ({ ); return transformSavedObjectToExceptionList({ savedObject }); } catch (err) { - if (savedObjectsClient.errors.isConflictError(err)) { + if (SavedObjectsErrorHelpers.isConflictError(err)) { return null; } else { throw err; diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_trusted_apps_list.ts b/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_trusted_apps_list.ts index 00b955cda8126..dcdae37b60094 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_trusted_apps_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_trusted_apps_list.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { SavedObjectsClientContract } from '@kbn/core/server'; +import { SavedObjectsClientContract, SavedObjectsErrorHelpers } from '@kbn/core/server'; import uuid from 'uuid'; import type { Version } from '@kbn/securitysolution-io-ts-types'; import type { ExceptionListSchema } from '@kbn/securitysolution-io-ts-list-types'; @@ -72,7 +72,7 @@ export const createEndpointTrustedAppsList = async ({ ); return transformSavedObjectToExceptionList({ savedObject }); } catch (err) { - if (savedObjectsClient.errors.isConflictError(err)) { + if (SavedObjectsErrorHelpers.isConflictError(err)) { return null; } else { throw err; From 4138fb68e2441fce2bb10a47ff501e08e23a0ae4 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 13:38:38 +0200 Subject: [PATCH 23/46] fix more internal imports --- src/core/public/saved_objects/saved_objects_service.ts | 5 ++++- src/core/public/saved_objects/simple_saved_object.test.ts | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/core/public/saved_objects/saved_objects_service.ts b/src/core/public/saved_objects/saved_objects_service.ts index 59550f58af69a..776e35700a0af 100644 --- a/src/core/public/saved_objects/saved_objects_service.ts +++ b/src/core/public/saved_objects/saved_objects_service.ts @@ -8,7 +8,8 @@ import type { CoreService } from '@kbn/core-base-browser-internal'; import type { HttpStart } from '@kbn/core-http-browser'; -import { SavedObjectsClient, type SavedObjectsClientContract } from './saved_objects_client'; +import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-browser'; +import { SavedObjectsClient } from './saved_objects_client'; /** * @public @@ -20,8 +21,10 @@ export interface SavedObjectsStart { export class SavedObjectsService implements CoreService { public async setup() {} + public async start({ http }: { http: HttpStart }): Promise { return { client: new SavedObjectsClient(http) }; } + public async stop() {} } diff --git a/src/core/public/saved_objects/simple_saved_object.test.ts b/src/core/public/saved_objects/simple_saved_object.test.ts index 432bc215a5b4c..1cbacb03dcfdf 100644 --- a/src/core/public/saved_objects/simple_saved_object.test.ts +++ b/src/core/public/saved_objects/simple_saved_object.test.ts @@ -6,9 +6,9 @@ * Side Public License, v 1. */ -import { SavedObject } from '../../server'; +import type { SavedObject } from '@kbn/core-saved-objects-common'; +import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-browser'; import { SimpleSavedObject } from './simple_saved_object'; -import { SavedObjectsClientContract } from './saved_objects_client'; describe('SimpleSavedObject', () => { let client: SavedObjectsClientContract; From 6240fc86c50f839345b44bfceda9c67d6b1b0061 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 13:52:30 +0200 Subject: [PATCH 24/46] use interface for SSO --- src/plugins/data_views/public/saved_objects_client_wrapper.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/plugins/data_views/public/saved_objects_client_wrapper.ts b/src/plugins/data_views/public/saved_objects_client_wrapper.ts index e8d008e130323..5f08b77ec832a 100644 --- a/src/plugins/data_views/public/saved_objects_client_wrapper.ts +++ b/src/plugins/data_views/public/saved_objects_client_wrapper.ts @@ -10,7 +10,7 @@ import { SavedObjectsClientContract, SavedObjectsCreateOptions, SavedObjectsUpdateOptions, - SimpleSavedObject, + ISimpleSavedObject, } from '@kbn/core/public'; import { omit } from 'lodash'; import { DataViewSavedObjectConflictError } from '../common/errors'; @@ -26,7 +26,7 @@ type SOClient = Pick< 'find' | 'resolve' | 'update' | 'create' | 'delete' >; -const simpleSavedObjectToSavedObject = (simpleSavedObject: SimpleSavedObject): SavedObject => +const simpleSavedObjectToSavedObject = (simpleSavedObject: ISimpleSavedObject): SavedObject => ({ version: simpleSavedObject._version, ...omit(simpleSavedObject, '_version'), From 1fefac4691eb6070149e34dff55c5b04e883e5f6 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 14:05:18 +0200 Subject: [PATCH 25/46] adapt more imports --- x-pack/plugins/spaces/public/legacy_urls/types.ts | 2 +- .../components/relatives_footer.tsx | 2 +- .../components/share_to_space_flyout_internal.test.tsx | 2 +- .../components/share_to_space_flyout_internal.tsx | 3 ++- .../plugins/spaces/public/spaces_manager/spaces_manager.ts | 6 ++---- 5 files changed, 7 insertions(+), 8 deletions(-) diff --git a/x-pack/plugins/spaces/public/legacy_urls/types.ts b/x-pack/plugins/spaces/public/legacy_urls/types.ts index da78792bcf35a..7ad3919d9d166 100644 --- a/x-pack/plugins/spaces/public/legacy_urls/types.ts +++ b/x-pack/plugins/spaces/public/legacy_urls/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { SavedObjectsResolveResponse } from '@kbn/core/public'; +import type { SavedObjectsResolveResponse } from '@kbn/core-saved-objects-api-server'; /** * Properties for the LegacyUrlConflict component. diff --git a/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/relatives_footer.tsx b/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/relatives_footer.tsx index d5f8f26fbfe97..a1092d3a680a5 100644 --- a/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/relatives_footer.tsx +++ b/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/relatives_footer.tsx @@ -8,7 +8,7 @@ import { EuiHorizontalRule, EuiText } from '@elastic/eui'; import React, { useMemo } from 'react'; -import type { SavedObjectReferenceWithContext } from '@kbn/core/public'; +import type { SavedObjectReferenceWithContext } from '@kbn/core-saved-objects-api-server'; import { FormattedMessage } from '@kbn/i18n-react'; import type { ShareToSpaceSavedObjectTarget } from '../types'; diff --git a/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/share_to_space_flyout_internal.test.tsx b/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/share_to_space_flyout_internal.test.tsx index 8d0ac4c27c642..8341e4a709311 100644 --- a/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/share_to_space_flyout_internal.test.tsx +++ b/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/share_to_space_flyout_internal.test.tsx @@ -11,7 +11,7 @@ import { act } from '@testing-library/react'; import type { ReactWrapper } from 'enzyme'; import React from 'react'; -import type { SavedObjectReferenceWithContext } from '@kbn/core/public'; +import type { SavedObjectReferenceWithContext } from '@kbn/core-saved-objects-api-server'; import { coreMock } from '@kbn/core/public/mocks'; import { findTestSubject, mountWithIntl, nextTick } from '@kbn/test-jest-helpers'; diff --git a/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/share_to_space_flyout_internal.tsx b/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/share_to_space_flyout_internal.tsx index 157b684e2c993..5d661d84f2a12 100644 --- a/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/share_to_space_flyout_internal.tsx +++ b/x-pack/plugins/spaces/public/share_saved_objects_to_space/components/share_to_space_flyout_internal.tsx @@ -23,7 +23,8 @@ import { } from '@elastic/eui'; import React, { lazy, Suspense, useEffect, useMemo, useState } from 'react'; -import type { SavedObjectReferenceWithContext, ToastsStart } from '@kbn/core/public'; +import type { SavedObjectReferenceWithContext } from '@kbn/core-saved-objects-api-server'; +import type { ToastsStart } from '@kbn/core/public'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; diff --git a/x-pack/plugins/spaces/public/spaces_manager/spaces_manager.ts b/x-pack/plugins/spaces/public/spaces_manager/spaces_manager.ts index 540667931e49b..50b9660dc0577 100644 --- a/x-pack/plugins/spaces/public/spaces_manager/spaces_manager.ts +++ b/x-pack/plugins/spaces/public/spaces_manager/spaces_manager.ts @@ -9,10 +9,8 @@ import type { Observable } from 'rxjs'; import { BehaviorSubject } from 'rxjs'; import { skipWhile } from 'rxjs/operators'; -import type { - HttpSetup, - SavedObjectsCollectMultiNamespaceReferencesResponse, -} from '@kbn/core/public'; +import type { SavedObjectsCollectMultiNamespaceReferencesResponse } from '@kbn/core-saved-objects-api-server'; +import type { HttpSetup } from '@kbn/core/public'; import type { GetAllSpacesOptions, From 567de0ab7582ada948deb38d5083edfa67e7cf50 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 14:17:14 +0200 Subject: [PATCH 26/46] damn those types were a mess --- src/plugins/data/public/search/session/sessions_client.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/plugins/data/public/search/session/sessions_client.ts b/src/plugins/data/public/search/session/sessions_client.ts index 71e8d9dafb78d..f05f7b794763e 100644 --- a/src/plugins/data/public/search/session/sessions_client.ts +++ b/src/plugins/data/public/search/session/sessions_client.ts @@ -7,11 +7,12 @@ */ import { PublicContract } from '@kbn/utility-types'; -import { HttpSetup, SavedObjectsFindOptions } from '@kbn/core/public'; +import { HttpSetup } from '@kbn/core/public'; import type { SavedObject, SavedObjectsFindResponse, SavedObjectsUpdateResponse, + SavedObjectsFindOptions, // eslint-disable-next-line @kbn/eslint/no-restricted-paths } from '@kbn/core/server'; import type { SearchSessionSavedObjectAttributes } from '../../../common'; From 07a12e5353459987ea090695f2f02c4a0ca0c9c8 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 14:31:37 +0200 Subject: [PATCH 27/46] fix more usages of SSO --- .../public/finder/saved_object_finder.tsx | 22 +++++++++---------- .../helpers/find_object_by_title.ts | 6 ++--- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/plugins/saved_objects/public/finder/saved_object_finder.tsx b/src/plugins/saved_objects/public/finder/saved_object_finder.tsx index 3eb5fd97142a1..444c97d8378b2 100644 --- a/src/plugins/saved_objects/public/finder/saved_object_finder.tsx +++ b/src/plugins/saved_objects/public/finder/saved_object_finder.tsx @@ -32,7 +32,7 @@ import { Direction } from '@elastic/eui/src/services/sort/sort_direction'; import { i18n } from '@kbn/i18n'; import { - SimpleSavedObject, + ISimpleSavedObject, CoreStart, IUiSettingsClient, SavedObjectsStart, @@ -43,10 +43,10 @@ import { LISTING_LIMIT_SETTING } from '../../common'; export interface SavedObjectMetaData { type: string; name: string; - getIconForSavedObject(savedObject: SimpleSavedObject): IconType; - getTooltipForSavedObject?(savedObject: SimpleSavedObject): string; - showSavedObject?(savedObject: SimpleSavedObject): boolean; - getSavedObjectSubType?(savedObject: SimpleSavedObject): string; + getIconForSavedObject(savedObject: ISimpleSavedObject): IconType; + getTooltipForSavedObject?(savedObject: ISimpleSavedObject): string; + showSavedObject?(savedObject: ISimpleSavedObject): boolean; + getSavedObjectSubType?(savedObject: ISimpleSavedObject): string; includeFields?: string[]; } @@ -60,9 +60,9 @@ interface SavedObjectFinderState { items: Array<{ title: string | null; name: string | null; - id: SimpleSavedObject['id']; - type: SimpleSavedObject['type']; - savedObject: SimpleSavedObject; + id: ISimpleSavedObject['id']; + type: ISimpleSavedObject['type']; + savedObject: ISimpleSavedObject; }>; query: string; isFetchingItems: boolean; @@ -76,10 +76,10 @@ interface SavedObjectFinderState { interface BaseSavedObjectFinder { onChoose?: ( - id: SimpleSavedObject['id'], - type: SimpleSavedObject['type'], + id: ISimpleSavedObject['id'], + type: ISimpleSavedObject['type'], name: string, - savedObject: SimpleSavedObject + savedObject: ISimpleSavedObject ) => void; noItemsMessage?: React.ReactNode; savedObjectMetaData: Array>; diff --git a/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.ts b/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.ts index 53b05265eecb7..e6786ee173fd5 100644 --- a/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.ts +++ b/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.ts @@ -8,7 +8,7 @@ import { SavedObjectsClientContract, - SimpleSavedObject, + ISimpleSavedObject, SavedObjectAttributes, } from '@kbn/core/public'; @@ -18,13 +18,13 @@ import { * @param savedObjectsClient {SavedObjectsClientContract} * @param type {string} * @param title {string} - * @returns {Promise} + * @returns {Promise} */ export async function findObjectByTitle( savedObjectsClient: SavedObjectsClientContract, type: string, title: string -): Promise | void> { +): Promise | void> { if (!title) { return; } From 7ee9822bb2b849e88396904a8867018da0ef7003 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 14:49:41 +0200 Subject: [PATCH 28/46] Revert "fix more usages of SSO" This reverts commit 07a12e5353459987ea090695f2f02c4a0ca0c9c8. --- .../public/finder/saved_object_finder.tsx | 22 +++++++++---------- .../helpers/find_object_by_title.ts | 6 ++--- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/plugins/saved_objects/public/finder/saved_object_finder.tsx b/src/plugins/saved_objects/public/finder/saved_object_finder.tsx index 444c97d8378b2..3eb5fd97142a1 100644 --- a/src/plugins/saved_objects/public/finder/saved_object_finder.tsx +++ b/src/plugins/saved_objects/public/finder/saved_object_finder.tsx @@ -32,7 +32,7 @@ import { Direction } from '@elastic/eui/src/services/sort/sort_direction'; import { i18n } from '@kbn/i18n'; import { - ISimpleSavedObject, + SimpleSavedObject, CoreStart, IUiSettingsClient, SavedObjectsStart, @@ -43,10 +43,10 @@ import { LISTING_LIMIT_SETTING } from '../../common'; export interface SavedObjectMetaData { type: string; name: string; - getIconForSavedObject(savedObject: ISimpleSavedObject): IconType; - getTooltipForSavedObject?(savedObject: ISimpleSavedObject): string; - showSavedObject?(savedObject: ISimpleSavedObject): boolean; - getSavedObjectSubType?(savedObject: ISimpleSavedObject): string; + getIconForSavedObject(savedObject: SimpleSavedObject): IconType; + getTooltipForSavedObject?(savedObject: SimpleSavedObject): string; + showSavedObject?(savedObject: SimpleSavedObject): boolean; + getSavedObjectSubType?(savedObject: SimpleSavedObject): string; includeFields?: string[]; } @@ -60,9 +60,9 @@ interface SavedObjectFinderState { items: Array<{ title: string | null; name: string | null; - id: ISimpleSavedObject['id']; - type: ISimpleSavedObject['type']; - savedObject: ISimpleSavedObject; + id: SimpleSavedObject['id']; + type: SimpleSavedObject['type']; + savedObject: SimpleSavedObject; }>; query: string; isFetchingItems: boolean; @@ -76,10 +76,10 @@ interface SavedObjectFinderState { interface BaseSavedObjectFinder { onChoose?: ( - id: ISimpleSavedObject['id'], - type: ISimpleSavedObject['type'], + id: SimpleSavedObject['id'], + type: SimpleSavedObject['type'], name: string, - savedObject: ISimpleSavedObject + savedObject: SimpleSavedObject ) => void; noItemsMessage?: React.ReactNode; savedObjectMetaData: Array>; diff --git a/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.ts b/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.ts index e6786ee173fd5..53b05265eecb7 100644 --- a/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.ts +++ b/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.ts @@ -8,7 +8,7 @@ import { SavedObjectsClientContract, - ISimpleSavedObject, + SimpleSavedObject, SavedObjectAttributes, } from '@kbn/core/public'; @@ -18,13 +18,13 @@ import { * @param savedObjectsClient {SavedObjectsClientContract} * @param type {string} * @param title {string} - * @returns {Promise} + * @returns {Promise} */ export async function findObjectByTitle( savedObjectsClient: SavedObjectsClientContract, type: string, title: string -): Promise | void> { +): Promise | void> { if (!title) { return; } From 878c14d94aaddb48766c6f346c68577e95d6c197 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 14:49:41 +0200 Subject: [PATCH 29/46] Revert "use interface for SSO" This reverts commit 6240fc86c50f839345b44bfceda9c67d6b1b0061. --- src/plugins/data_views/public/saved_objects_client_wrapper.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/plugins/data_views/public/saved_objects_client_wrapper.ts b/src/plugins/data_views/public/saved_objects_client_wrapper.ts index 5f08b77ec832a..e8d008e130323 100644 --- a/src/plugins/data_views/public/saved_objects_client_wrapper.ts +++ b/src/plugins/data_views/public/saved_objects_client_wrapper.ts @@ -10,7 +10,7 @@ import { SavedObjectsClientContract, SavedObjectsCreateOptions, SavedObjectsUpdateOptions, - ISimpleSavedObject, + SimpleSavedObject, } from '@kbn/core/public'; import { omit } from 'lodash'; import { DataViewSavedObjectConflictError } from '../common/errors'; @@ -26,7 +26,7 @@ type SOClient = Pick< 'find' | 'resolve' | 'update' | 'create' | 'delete' >; -const simpleSavedObjectToSavedObject = (simpleSavedObject: ISimpleSavedObject): SavedObject => +const simpleSavedObjectToSavedObject = (simpleSavedObject: SimpleSavedObject): SavedObject => ({ version: simpleSavedObject._version, ...omit(simpleSavedObject, '_version'), From ef08ef5cac4b12c2abd5fb55173b0fd271b00573 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 14:56:24 +0200 Subject: [PATCH 30/46] export the interface with the old name instead. --- .../core-saved-objects-api-browser/src/apis/base.ts | 4 ++-- .../core-saved-objects-api-browser/src/apis/resolve.ts | 4 ++-- .../core-saved-objects-api-browser/src/index.ts | 2 +- .../src/saved_objects_client.ts | 8 ++++---- .../src/simple_saved_object.ts | 4 ++-- src/core/public/index.ts | 5 ++--- src/core/public/saved_objects/index.ts | 2 +- .../public/saved_objects/saved_objects_client.test.ts | 2 +- src/core/public/saved_objects/saved_objects_client.ts | 7 ++++--- src/core/public/saved_objects/simple_saved_object.ts | 10 +++++----- 10 files changed, 24 insertions(+), 24 deletions(-) diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/base.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/base.ts index 5a741d95c58b6..6414b206a672b 100644 --- a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/base.ts +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/base.ts @@ -6,9 +6,9 @@ * Side Public License, v 1. */ -import { ISimpleSavedObject } from '../simple_saved_object'; +import { SimpleSavedObject } from '../simple_saved_object'; /** @public */ export interface SavedObjectsBatchResponse { - savedObjects: Array>; + savedObjects: Array>; } diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/resolve.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/resolve.ts index 2436a34423f94..c2383d7cb50d5 100644 --- a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/resolve.ts +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/resolve.ts @@ -7,7 +7,7 @@ */ import type { SavedObjectsResolveResponse } from '@kbn/core-saved-objects-api-server'; -import { ISimpleSavedObject } from '../simple_saved_object'; +import { SimpleSavedObject } from '../simple_saved_object'; /** * This interface is a very simple wrapper for SavedObjects resolved from the server @@ -19,7 +19,7 @@ export interface ResolvedSimpleSavedObject { /** * The saved object that was found. */ - saved_object: ISimpleSavedObject; + saved_object: SimpleSavedObject; /** * The outcome for a successful `resolve` call is one of the following values: * diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/index.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/index.ts index 336e25838ea92..929ae5b95ebeb 100644 --- a/packages/core/saved-objects/core-saved-objects-api-browser/src/index.ts +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/index.ts @@ -7,7 +7,7 @@ */ export type { SavedObjectsClientContract } from './saved_objects_client'; -export type { ISimpleSavedObject } from './simple_saved_object'; +export type { SimpleSavedObject } from './simple_saved_object'; export type { SavedObjectsCreateOptions, SavedObjectsDeleteOptions, diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/saved_objects_client.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/saved_objects_client.ts index 5741e05ccddc1..123b5c81d4064 100644 --- a/packages/core/saved-objects/core-saved-objects-api-browser/src/saved_objects_client.ts +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/saved_objects_client.ts @@ -20,7 +20,7 @@ import type { SavedObjectsUpdateOptions, SavedObjectsDeleteOptions, } from './apis'; -import type { ISimpleSavedObject } from './simple_saved_object'; +import type { SimpleSavedObject } from './simple_saved_object'; /** * The client-side SavedObjectsClient is a thin convenience library around the SavedObjects @@ -36,7 +36,7 @@ export interface SavedObjectsClientContract { type: string, attributes: T, options?: SavedObjectsCreateOptions - ): Promise>; + ): Promise>; /** * Creates multiple documents at once @@ -77,7 +77,7 @@ export interface SavedObjectsClientContract { * @param {string} id * @returns The saved object for the given type and id. */ - get(type: string, id: string): Promise>; + get(type: string, id: string): Promise>; /** * Returns an array of objects by id @@ -143,7 +143,7 @@ export interface SavedObjectsClientContract { id: string, attributes: T, options?: SavedObjectsUpdateOptions - ): Promise>; + ): Promise>; /** * Update multiple documents at once diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/simple_saved_object.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/simple_saved_object.ts index ed4a602538544..46d3e65cdec1b 100644 --- a/packages/core/saved-objects/core-saved-objects-api-browser/src/simple_saved_object.ts +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/simple_saved_object.ts @@ -17,7 +17,7 @@ import type { SavedObject as SavedObjectType } from '@kbn/core-saved-objects-com * * @public */ -export interface ISimpleSavedObject { +export interface SimpleSavedObject { attributes: T; _version?: SavedObjectType['version']; id: SavedObjectType['id']; @@ -39,7 +39,7 @@ export interface ISimpleSavedObject { has(key: string): boolean; - save(): Promise>; + save(): Promise>; delete(): Promise<{}>; } diff --git a/src/core/public/index.ts b/src/core/public/index.ts index 732186321e213..bab7dfbe3248d 100644 --- a/src/core/public/index.ts +++ b/src/core/public/index.ts @@ -127,11 +127,10 @@ export type { NavigateToUrlOptions, } from './application'; -// TODO: check if can be exported as type. -export { SimpleSavedObject } from './saved_objects'; +export { SimpleSavedObjectImpl } from './saved_objects'; export type { SavedObjectsClientContract, - ISimpleSavedObject, + SimpleSavedObject, SavedObjectsCreateOptions, SavedObjectsDeleteOptions, SavedObjectsBatchResponse, diff --git a/src/core/public/saved_objects/index.ts b/src/core/public/saved_objects/index.ts index ae482df225a48..cb3ab31cea5c8 100644 --- a/src/core/public/saved_objects/index.ts +++ b/src/core/public/saved_objects/index.ts @@ -8,5 +8,5 @@ export { SavedObjectsService } from './saved_objects_service'; export type { SavedObjectsClient } from './saved_objects_client'; -export { SimpleSavedObject } from './simple_saved_object'; +export { SimpleSavedObjectImpl } from './simple_saved_object'; export type { SavedObjectsStart } from './saved_objects_service'; diff --git a/src/core/public/saved_objects/saved_objects_client.test.ts b/src/core/public/saved_objects/saved_objects_client.test.ts index ebc58218eb9d1..77391343cd033 100644 --- a/src/core/public/saved_objects/saved_objects_client.test.ts +++ b/src/core/public/saved_objects/saved_objects_client.test.ts @@ -8,7 +8,7 @@ import { httpServiceMock } from '@kbn/core-http-browser-mocks'; import { SavedObjectsClient } from './saved_objects_client'; -import { SimpleSavedObject } from './simple_saved_object'; +import { SimpleSavedObjectImpl as SimpleSavedObject } from './simple_saved_object'; describe('SavedObjectsClient', () => { const doc = { diff --git a/src/core/public/saved_objects/saved_objects_client.ts b/src/core/public/saved_objects/saved_objects_client.ts index 616daf0fc5c54..3a16030983fa9 100644 --- a/src/core/public/saved_objects/saved_objects_client.ts +++ b/src/core/public/saved_objects/saved_objects_client.ts @@ -27,9 +27,10 @@ import type { SavedObjectsFindResponse, SavedObjectsBulkCreateOptions, SavedObjectsBulkCreateObject, + SimpleSavedObject, } from '@kbn/core-saved-objects-api-browser'; -import { SimpleSavedObject } from './simple_saved_object'; +import { SimpleSavedObjectImpl } from './simple_saved_object'; type PromiseType> = T extends Promise ? U : never; @@ -423,13 +424,13 @@ export class SavedObjectsClient implements SavedObjectsClientContract { } private createSavedObject(options: SavedObject): SimpleSavedObject { - return new SimpleSavedObject(this, options); + return new SimpleSavedObjectImpl(this, options); } private createResolvedSavedObject( resolveResponse: SavedObjectsResolveResponse ): ResolvedSimpleSavedObject { - const simpleSavedObject = new SimpleSavedObject(this, resolveResponse.saved_object); + const simpleSavedObject = new SimpleSavedObjectImpl(this, resolveResponse.saved_object); return { saved_object: simpleSavedObject, outcome: resolveResponse.outcome, diff --git a/src/core/public/saved_objects/simple_saved_object.ts b/src/core/public/saved_objects/simple_saved_object.ts index 7caa83c2f784e..89501c69dcfb5 100644 --- a/src/core/public/saved_objects/simple_saved_object.ts +++ b/src/core/public/saved_objects/simple_saved_object.ts @@ -11,15 +11,15 @@ import { get, has } from 'lodash'; import type { SavedObject as SavedObjectType } from '@kbn/core-saved-objects-common'; import type { SavedObjectsClientContract, - ISimpleSavedObject, + SimpleSavedObject, } from '@kbn/core-saved-objects-api-browser'; /** - * Core internal implementation of {@link ISimpleSavedObject} + * Core internal implementation of {@link SimpleSavedObject} * - * @public + * @internal Should use the {@link SimpleSavedObject} interface instead */ -export class SimpleSavedObject implements ISimpleSavedObject { +export class SimpleSavedObjectImpl implements SimpleSavedObject { public attributes: T; public _version?: SavedObjectType['version']; public id: SavedObjectType['id']; @@ -72,7 +72,7 @@ export class SimpleSavedObject implements ISimpleSavedObject { return has(this.attributes, key); } - public save(): Promise> { + public save(): Promise> { if (this.id) { return this.client .update(this.type, this.id, this.attributes, { From 14dd79f06886227f5238bf94f047f724d55d98bb Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 15:06:06 +0200 Subject: [PATCH 31/46] adapt tests concrete usages of SSO --- src/core/public/saved_objects/simple_saved_object.test.ts | 4 ++-- .../public/saved_object/helpers/find_object_by_title.test.ts | 4 ++-- .../utils/saved_objects_utils/find_object_by_title.test.ts | 4 ++-- .../saved_objects_utils/find_object_by_title.test.ts | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/core/public/saved_objects/simple_saved_object.test.ts b/src/core/public/saved_objects/simple_saved_object.test.ts index 1cbacb03dcfdf..7ffe708fd1e12 100644 --- a/src/core/public/saved_objects/simple_saved_object.test.ts +++ b/src/core/public/saved_objects/simple_saved_object.test.ts @@ -8,9 +8,9 @@ import type { SavedObject } from '@kbn/core-saved-objects-common'; import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-browser'; -import { SimpleSavedObject } from './simple_saved_object'; +import { SimpleSavedObjectImpl as SimpleSavedObject } from './simple_saved_object'; -describe('SimpleSavedObject', () => { +describe('SimpleSavedObjectImpl', () => { let client: SavedObjectsClientContract; beforeEach(() => { diff --git a/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.test.ts b/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.test.ts index 398c00b27e4e9..a6479bbbefeb0 100644 --- a/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.test.ts +++ b/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.test.ts @@ -7,7 +7,7 @@ */ import { findObjectByTitle } from './find_object_by_title'; -import { SimpleSavedObject, SavedObjectsClientContract, SavedObject } from '@kbn/core/public'; +import { SimpleSavedObjectImpl, SavedObjectsClientContract, SavedObject } from '@kbn/core/public'; describe('findObjectByTitle', () => { const savedObjectsClient: SavedObjectsClientContract = {} as SavedObjectsClientContract; @@ -22,7 +22,7 @@ describe('findObjectByTitle', () => { }); it('matches any case', async () => { - const indexPattern = new SimpleSavedObject(savedObjectsClient, { + const indexPattern = new SimpleSavedObjectImpl(savedObjectsClient, { attributes: { title: 'foo' }, } as SavedObject); savedObjectsClient.find = jest.fn().mockImplementation(() => diff --git a/src/plugins/visualizations/public/utils/saved_objects_utils/find_object_by_title.test.ts b/src/plugins/visualizations/public/utils/saved_objects_utils/find_object_by_title.test.ts index 398c00b27e4e9..a6479bbbefeb0 100644 --- a/src/plugins/visualizations/public/utils/saved_objects_utils/find_object_by_title.test.ts +++ b/src/plugins/visualizations/public/utils/saved_objects_utils/find_object_by_title.test.ts @@ -7,7 +7,7 @@ */ import { findObjectByTitle } from './find_object_by_title'; -import { SimpleSavedObject, SavedObjectsClientContract, SavedObject } from '@kbn/core/public'; +import { SimpleSavedObjectImpl, SavedObjectsClientContract, SavedObject } from '@kbn/core/public'; describe('findObjectByTitle', () => { const savedObjectsClient: SavedObjectsClientContract = {} as SavedObjectsClientContract; @@ -22,7 +22,7 @@ describe('findObjectByTitle', () => { }); it('matches any case', async () => { - const indexPattern = new SimpleSavedObject(savedObjectsClient, { + const indexPattern = new SimpleSavedObjectImpl(savedObjectsClient, { attributes: { title: 'foo' }, } as SavedObject); savedObjectsClient.find = jest.fn().mockImplementation(() => diff --git a/x-pack/plugins/lens/public/persistence/saved_objects_utils/find_object_by_title.test.ts b/x-pack/plugins/lens/public/persistence/saved_objects_utils/find_object_by_title.test.ts index a07a20ee1f284..aadc35068da0e 100644 --- a/x-pack/plugins/lens/public/persistence/saved_objects_utils/find_object_by_title.test.ts +++ b/x-pack/plugins/lens/public/persistence/saved_objects_utils/find_object_by_title.test.ts @@ -6,7 +6,7 @@ */ import { findObjectByTitle } from './find_object_by_title'; -import { SimpleSavedObject, SavedObjectsClientContract, SavedObject } from '@kbn/core/public'; +import { SimpleSavedObjectImpl, SavedObjectsClientContract, SavedObject } from '@kbn/core/public'; describe('findObjectByTitle', () => { const savedObjectsClient: SavedObjectsClientContract = {} as SavedObjectsClientContract; @@ -21,7 +21,7 @@ describe('findObjectByTitle', () => { }); it('matches any case', async () => { - const indexPattern = new SimpleSavedObject(savedObjectsClient, { + const indexPattern = new SimpleSavedObjectImpl(savedObjectsClient, { attributes: { title: 'foo' }, } as SavedObject); savedObjectsClient.find = jest.fn().mockImplementation(() => From 70a82e4edcb178accdca1de1b9b471f46760def9 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 15:33:54 +0200 Subject: [PATCH 32/46] export reference type, more fixes --- .../core-saved-objects-api-browser/src/apis/find.ts | 8 ++++++++ .../core-saved-objects-api-browser/src/apis/index.ts | 6 +++++- .../core-saved-objects-api-browser/src/index.ts | 1 + src/core/public/index.ts | 1 + .../discover/public/services/saved_searches/types.ts | 2 +- .../plugins/graph/public/helpers/use_workspace_loader.ts | 2 +- 6 files changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/find.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/find.ts index 61e11915b6348..7f555764124a0 100644 --- a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/find.ts +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/find.ts @@ -29,3 +29,11 @@ export interface SavedObjectsFindResponse perPage: number; page: number; } + +/** + * @public + */ +export interface SavedObjectsFindOptionsReference { + type: string; + id: string; +} diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/index.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/index.ts index 3c7a8748212f8..4652facb972cc 100644 --- a/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/index.ts +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/apis/index.ts @@ -12,6 +12,10 @@ export type { SavedObjectsBulkResolveResponse } from './bulk_resolve'; export type { SavedObjectsBulkUpdateObject, SavedObjectsBulkUpdateOptions } from './bulk_update'; export type { SavedObjectsCreateOptions } from './create'; export type { SavedObjectsDeleteOptions } from './delete'; -export type { SavedObjectsFindResponse, SavedObjectsFindOptions } from './find'; +export type { + SavedObjectsFindResponse, + SavedObjectsFindOptions, + SavedObjectsFindOptionsReference, +} from './find'; export type { ResolvedSimpleSavedObject } from './resolve'; export type { SavedObjectsUpdateOptions } from './update'; diff --git a/packages/core/saved-objects/core-saved-objects-api-browser/src/index.ts b/packages/core/saved-objects/core-saved-objects-api-browser/src/index.ts index 929ae5b95ebeb..82a93cf091c77 100644 --- a/packages/core/saved-objects/core-saved-objects-api-browser/src/index.ts +++ b/packages/core/saved-objects/core-saved-objects-api-browser/src/index.ts @@ -13,6 +13,7 @@ export type { SavedObjectsDeleteOptions, SavedObjectsBatchResponse, SavedObjectsFindOptions, + SavedObjectsFindOptionsReference, SavedObjectsUpdateOptions, ResolvedSimpleSavedObject, SavedObjectsBulkUpdateObject, diff --git a/src/core/public/index.ts b/src/core/public/index.ts index bab7dfbe3248d..2a66d397b74e7 100644 --- a/src/core/public/index.ts +++ b/src/core/public/index.ts @@ -135,6 +135,7 @@ export type { SavedObjectsDeleteOptions, SavedObjectsBatchResponse, SavedObjectsFindOptions, + SavedObjectsFindOptionsReference, SavedObjectsUpdateOptions, ResolvedSimpleSavedObject, SavedObjectsBulkUpdateObject, diff --git a/src/plugins/discover/public/services/saved_searches/types.ts b/src/plugins/discover/public/services/saved_searches/types.ts index 1e81c9e88c8a3..8cdf18616f356 100644 --- a/src/plugins/discover/public/services/saved_searches/types.ts +++ b/src/plugins/discover/public/services/saved_searches/types.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import type { SavedObjectsResolveResponse } from '@kbn/core/public'; +import type { SavedObjectsResolveResponse } from '@kbn/core-saved-objects-api-server'; import type { ISearchSource } from '@kbn/data-plugin/public'; import { DiscoverGridSettingsColumn } from '../../components/discover_grid/types'; import { VIEW_MODE } from '../../components/view_mode_toggle'; diff --git a/x-pack/plugins/graph/public/helpers/use_workspace_loader.ts b/x-pack/plugins/graph/public/helpers/use_workspace_loader.ts index 1e50a951e16b1..d878f001f2984 100644 --- a/x-pack/plugins/graph/public/helpers/use_workspace_loader.ts +++ b/x-pack/plugins/graph/public/helpers/use_workspace_loader.ts @@ -8,7 +8,7 @@ import { useEffect, useState } from 'react'; import { useHistory, useLocation, useParams } from 'react-router-dom'; import type { SavedObjectsClientContract } from '@kbn/core/public'; -import type { SavedObjectsResolveResponse } from '@kbn/core/public'; +import type { SavedObjectsResolveResponse } from '@kbn/core-saved-objects-api-server'; import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; import { i18n } from '@kbn/i18n'; import { CoreStart } from '@kbn/core/public'; From ded32bf653dc837c407a984943b6add97b38c724 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 15:54:09 +0200 Subject: [PATCH 33/46] this gonna be long --- .../objects_table/saved_objects_table.tsx | 2 +- src/plugins/visualizations/public/types.ts | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.tsx b/src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.tsx index b0afbcc163ef8..e1fd031596855 100644 --- a/src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.tsx +++ b/src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.tsx @@ -14,12 +14,12 @@ import { EuiSpacer, Query, CriteriaWithPagination } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { SavedObjectsClientContract, - SavedObjectsFindOptions, HttpStart, OverlayStart, NotificationsStart, ApplicationStart, } from '@kbn/core/public'; +import type { SavedObjectsFindOptions } from '@kbn/core-saved-objects-api-server'; import { RedirectAppLinks } from '@kbn/kibana-react-plugin/public'; import { SavedObjectsTaggingApi } from '@kbn/saved-objects-tagging-oss-plugin/public'; import { DataViewsContract } from '@kbn/data-views-plugin/public'; diff --git a/src/plugins/visualizations/public/types.ts b/src/plugins/visualizations/public/types.ts index 9235b62c11bd9..8c09258f83546 100644 --- a/src/plugins/visualizations/public/types.ts +++ b/src/plugins/visualizations/public/types.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import type { SavedObjectsMigrationVersion, SavedObjectsResolveResponse } from '@kbn/core/public'; +import type { SavedObjectsMigrationVersion, ResolvedSimpleSavedObject } from '@kbn/core/public'; import { IAggConfigs, SerializedSearchSourceFields, @@ -38,9 +38,9 @@ export interface ISavedVis { savedSearchRefName?: string; savedSearchId?: string; sharingSavedObjectProps?: { - outcome?: SavedObjectsResolveResponse['outcome']; - aliasTargetId?: SavedObjectsResolveResponse['alias_target_id']; - aliasPurpose?: SavedObjectsResolveResponse['alias_purpose']; + outcome?: ResolvedSimpleSavedObject['outcome']; + aliasTargetId?: ResolvedSimpleSavedObject['alias_target_id']; + aliasPurpose?: ResolvedSimpleSavedObject['alias_purpose']; errorJSON?: string; }; } From 167d5d8c33902b79466d49c4052a56d8578c8ae8 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 16:13:42 +0200 Subject: [PATCH 34/46] one more --- x-pack/plugins/lens/public/types.ts | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/x-pack/plugins/lens/public/types.ts b/x-pack/plugins/lens/public/types.ts index ecd27d7a3387d..54947670e8551 100644 --- a/x-pack/plugins/lens/public/types.ts +++ b/x-pack/plugins/lens/public/types.ts @@ -6,11 +6,7 @@ */ import { Ast } from '@kbn/interpreter'; import type { IconType } from '@elastic/eui/src/components/icon/icon'; -import type { - CoreSetup, - SavedObjectReference, - SavedObjectsResolveResponse, -} from '@kbn/core/public'; +import type { CoreSetup, SavedObjectReference, ResolvedSimpleSavedObject } from '@kbn/core/public'; import type { PaletteOutput } from '@kbn/coloring'; import type { TopNavMenuData } from '@kbn/navigation-plugin/public'; import type { MutableRefObject } from 'react'; @@ -618,6 +614,7 @@ export interface VisualizationDimensionChangeProps { prevState: T; frame: FramePublicAPI; } + export interface Suggestion { visualizationId: string; datasourceState?: unknown; @@ -720,6 +717,7 @@ export interface FramePublicAPI { */ activeData?: Record; } + export interface FrameDatasourceAPI extends FramePublicAPI { query: Query; filters: Filter[]; @@ -1020,9 +1018,9 @@ export interface ILensInterpreterRenderHandlers extends IInterpreterRenderHandle } export interface SharingSavedObjectProps { - outcome?: SavedObjectsResolveResponse['outcome']; - aliasTargetId?: SavedObjectsResolveResponse['alias_target_id']; - aliasPurpose?: SavedObjectsResolveResponse['alias_purpose']; + outcome?: ResolvedSimpleSavedObject['outcome']; + aliasTargetId?: ResolvedSimpleSavedObject['alias_target_id']; + aliasPurpose?: ResolvedSimpleSavedObject['alias_purpose']; sourceId?: string; } From 3b3b77c117fa7446ef8df81883d9860e312cfa9d Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 16:42:35 +0200 Subject: [PATCH 35/46] other resolve type change --- x-pack/plugins/cases/common/ui/types.ts | 9 +++++---- x-pack/plugins/maps/public/map_attribute_service.ts | 8 ++++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/x-pack/plugins/cases/common/ui/types.ts b/x-pack/plugins/cases/common/ui/types.ts index 59ca060bba78e..ac4a9b6e14b1e 100644 --- a/x-pack/plugins/cases/common/ui/types.ts +++ b/x-pack/plugins/cases/common/ui/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { SavedObjectsResolveResponse } from '@kbn/core/public'; +import type { ResolvedSimpleSavedObject } from '@kbn/core/public'; import { CREATE_CASES_CAPABILITY, DELETE_CASES_CAPABILITY, @@ -85,9 +85,9 @@ export type CasesMetrics = SnakeToCamelCase; export interface ResolvedCase { case: Case; - outcome: SavedObjectsResolveResponse['outcome']; - aliasTargetId?: SavedObjectsResolveResponse['alias_target_id']; - aliasPurpose?: SavedObjectsResolveResponse['alias_purpose']; + outcome: ResolvedSimpleSavedObject['outcome']; + aliasTargetId?: ResolvedSimpleSavedObject['alias_target_id']; + aliasPurpose?: ResolvedSimpleSavedObject['alias_purpose']; } export interface QueryParams { @@ -140,6 +140,7 @@ export interface BulkUpdateStatus { id: string; version: string; } + export interface ActionLicense { id: string; name: string; diff --git a/x-pack/plugins/maps/public/map_attribute_service.ts b/x-pack/plugins/maps/public/map_attribute_service.ts index 8ede3e8911461..ce1d59f5b328c 100644 --- a/x-pack/plugins/maps/public/map_attribute_service.ts +++ b/x-pack/plugins/maps/public/map_attribute_service.ts @@ -6,7 +6,7 @@ */ import { SavedObjectReference } from '@kbn/core/types'; -import type { SavedObjectsResolveResponse } from '@kbn/core/public'; +import type { ResolvedSimpleSavedObject } from '@kbn/core/public'; import { AttributeService } from '@kbn/embeddable-plugin/public'; import { checkForDuplicateTitle, OnSaveProps } from '@kbn/saved-objects-plugin/public'; import { MapSavedObjectAttributes } from '../common/map_saved_object_type'; @@ -17,9 +17,9 @@ import { extractReferences, injectReferences } from '../common/migrations/refere import { MapByValueInput, MapByReferenceInput } from './embeddable/types'; export interface SharingSavedObjectProps { - outcome?: SavedObjectsResolveResponse['outcome']; - aliasTargetId?: SavedObjectsResolveResponse['alias_target_id']; - aliasPurpose?: SavedObjectsResolveResponse['alias_purpose']; + outcome?: ResolvedSimpleSavedObject['outcome']; + aliasTargetId?: ResolvedSimpleSavedObject['alias_target_id']; + aliasPurpose?: ResolvedSimpleSavedObject['alias_purpose']; sourceId?: string; } From 592398077d85e56dba92d1d60cfbbf8b41f290e6 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 17:07:22 +0200 Subject: [PATCH 36/46] more usages --- x-pack/plugins/canvas/public/services/workpad.ts | 8 ++++---- .../server/routes/custom_elements/create.test.ts | 9 +++++++-- .../server/routes/custom_elements/delete.test.ts | 9 +++++++-- .../server/routes/custom_elements/get.test.ts | 9 +++++++-- .../server/routes/custom_elements/update.test.ts | 13 ++++++++----- .../canvas/server/routes/workpad/create.test.ts | 4 ++-- .../canvas/server/routes/workpad/delete.test.ts | 9 +++++++-- .../canvas/server/routes/workpad/get.test.ts | 7 +++---- .../canvas/server/routes/workpad/resolve.test.ts | 7 +++---- .../canvas/server/routes/workpad/update.test.ts | 8 +++----- x-pack/plugins/infra/server/lib/sources/sources.ts | 8 ++++++-- .../server/services/log_views/log_views_client.ts | 3 ++- 12 files changed, 59 insertions(+), 35 deletions(-) diff --git a/x-pack/plugins/canvas/public/services/workpad.ts b/x-pack/plugins/canvas/public/services/workpad.ts index 1b4b912365e3a..82a29cea8de21 100644 --- a/x-pack/plugins/canvas/public/services/workpad.ts +++ b/x-pack/plugins/canvas/public/services/workpad.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { SavedObjectsResolveResponse } from '@kbn/core/public'; +import { ResolvedSimpleSavedObject } from '@kbn/core/public'; import { CanvasWorkpad, CanvasTemplate } from '../../types'; import { CanvasRenderedWorkpad } from '../../shareable_runtime/types'; @@ -22,9 +22,9 @@ export interface TemplateFindResponse { export interface ResolveWorkpadResponse { workpad: CanvasWorkpad; - outcome: SavedObjectsResolveResponse['outcome']; - aliasId?: SavedObjectsResolveResponse['alias_target_id']; - aliasPurpose?: SavedObjectsResolveResponse['alias_purpose']; + outcome: ResolvedSimpleSavedObject['outcome']; + aliasId?: ResolvedSimpleSavedObject['alias_target_id']; + aliasPurpose?: ResolvedSimpleSavedObject['alias_purpose']; } export interface CanvasWorkpadService { diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/create.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/create.test.ts index 69bb51de7d5c5..5c255c35f305f 100644 --- a/x-pack/plugins/canvas/server/routes/custom_elements/create.test.ts +++ b/x-pack/plugins/canvas/server/routes/custom_elements/create.test.ts @@ -10,7 +10,12 @@ import { AwaitedProperties } from '@kbn/utility-types'; import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks'; import { CUSTOM_ELEMENT_TYPE } from '../../../common/lib/constants'; import { initializeCreateCustomElementRoute } from './create'; -import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server'; +import { + kibanaResponseFactory, + RequestHandlerContext, + RequestHandler, + SavedObjectsErrorHelpers, +} from '@kbn/core/server'; import { getMockedRouterDeps } from '../test_helpers'; const mockRouteContext = { @@ -84,7 +89,7 @@ describe('POST custom element', () => { }); (mockRouteContext.core.savedObjects.client.create as jest.Mock).mockImplementation(() => { - throw mockRouteContext.core.savedObjects.client.errors.createBadRequestError('bad request'); + throw SavedObjectsErrorHelpers.createBadRequestError('bad request'); }); const response = await routeHandler( diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/delete.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/delete.test.ts index e989f1c7741f6..72b6d3dbdb9ef 100644 --- a/x-pack/plugins/canvas/server/routes/custom_elements/delete.test.ts +++ b/x-pack/plugins/canvas/server/routes/custom_elements/delete.test.ts @@ -8,7 +8,12 @@ import { AwaitedProperties } from '@kbn/utility-types'; import { CUSTOM_ELEMENT_TYPE } from '../../../common/lib/constants'; import { initializeDeleteCustomElementRoute } from './delete'; -import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server'; +import { + kibanaResponseFactory, + RequestHandlerContext, + RequestHandler, + SavedObjectsErrorHelpers, +} from '@kbn/core/server'; import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks'; import { getMockedRouterDeps } from '../test_helpers'; @@ -64,7 +69,7 @@ describe('DELETE custom element', () => { }); (mockRouteContext.core.savedObjects.client.delete as jest.Mock).mockImplementationOnce(() => { - throw mockRouteContext.core.savedObjects.client.errors.createBadRequestError('bad request'); + throw SavedObjectsErrorHelpers.createBadRequestError('bad request'); }); const response = await routeHandler( diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/get.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/get.test.ts index e12b1840d58c4..ac3081ea850d2 100644 --- a/x-pack/plugins/canvas/server/routes/custom_elements/get.test.ts +++ b/x-pack/plugins/canvas/server/routes/custom_elements/get.test.ts @@ -8,7 +8,12 @@ import { AwaitedProperties } from '@kbn/utility-types'; import { CUSTOM_ELEMENT_TYPE } from '../../../common/lib/constants'; import { initializeGetCustomElementRoute } from './get'; -import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server'; +import { + kibanaResponseFactory, + RequestHandlerContext, + RequestHandler, + SavedObjectsErrorHelpers, +} from '@kbn/core/server'; import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks'; import { getMockedRouterDeps } from '../test_helpers'; @@ -85,7 +90,7 @@ describe('GET custom element', () => { const savedObjectsClient = savedObjectsClientMock.create(); savedObjectsClient.get.mockImplementation(() => { - throw savedObjectsClient.errors.createGenericNotFoundError(CUSTOM_ELEMENT_TYPE, id); + throw SavedObjectsErrorHelpers.createGenericNotFoundError(CUSTOM_ELEMENT_TYPE, id); }); mockRouteContext.core.savedObjects.client = savedObjectsClient; diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/update.test.ts b/x-pack/plugins/canvas/server/routes/custom_elements/update.test.ts index cc24f5ad708ab..92dbf35bcf8aa 100644 --- a/x-pack/plugins/canvas/server/routes/custom_elements/update.test.ts +++ b/x-pack/plugins/canvas/server/routes/custom_elements/update.test.ts @@ -10,7 +10,12 @@ import { AwaitedProperties } from '@kbn/utility-types'; import { CustomElement } from '../../../types'; import { CUSTOM_ELEMENT_TYPE } from '../../../common/lib/constants'; import { initializeUpdateCustomElementRoute } from './update'; -import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server'; +import { + kibanaResponseFactory, + RequestHandlerContext, + RequestHandler, + SavedObjectsErrorHelpers, +} from '@kbn/core/server'; import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks'; import { okResponse } from '../ok_response'; import { getMockedRouterDeps } from '../test_helpers'; @@ -117,9 +122,7 @@ describe('PUT custom element', () => { }); (mockRouteContext.core.savedObjects.client.get as jest.Mock).mockImplementationOnce(() => { - throw mockRouteContext.core.savedObjects.client.errors.createGenericNotFoundError( - 'not found' - ); + throw SavedObjectsErrorHelpers.createGenericNotFoundError('not found'); }); const response = await routeHandler( @@ -150,7 +153,7 @@ describe('PUT custom element', () => { mockRouteContext.core.savedObjects.client = savedObjectsClient; (mockRouteContext.core.savedObjects.client.create as jest.Mock).mockImplementationOnce(() => { - throw mockRouteContext.core.savedObjects.client.errors.createBadRequestError('bad request'); + throw SavedObjectsErrorHelpers.createBadRequestError('bad request'); }); const response = await routeHandler( diff --git a/x-pack/plugins/canvas/server/routes/workpad/create.test.ts b/x-pack/plugins/canvas/server/routes/workpad/create.test.ts index 304d7864950e4..e409e342fe16e 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/create.test.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/create.test.ts @@ -9,7 +9,7 @@ import { AwaitedProperties } from '@kbn/utility-types'; import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks'; import { workpadRouteContextMock, MockWorkpadRouteContext } from '../../mocks'; import { initializeCreateWorkpadRoute } from './create'; -import { kibanaResponseFactory, RequestHandler } from '@kbn/core/server'; +import { kibanaResponseFactory, RequestHandler, SavedObjectsErrorHelpers } from '@kbn/core/server'; import { getMockedRouterDeps } from '../test_helpers'; let mockRouteContext = { @@ -77,7 +77,7 @@ describe('POST workpad', () => { }); mockRouteContext.canvas.workpad.create.mockImplementation(() => { - throw mockRouteContext.core.savedObjects.client.errors.createBadRequestError('bad request'); + throw SavedObjectsErrorHelpers.createBadRequestError('bad request'); }); const response = await routeHandler( diff --git a/x-pack/plugins/canvas/server/routes/workpad/delete.test.ts b/x-pack/plugins/canvas/server/routes/workpad/delete.test.ts index f29bad869a8a6..c0f7e31729817 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/delete.test.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/delete.test.ts @@ -8,7 +8,12 @@ import { AwaitedProperties } from '@kbn/utility-types'; import { CANVAS_TYPE } from '../../../common/lib/constants'; import { initializeDeleteWorkpadRoute } from './delete'; -import { kibanaResponseFactory, RequestHandlerContext, RequestHandler } from '@kbn/core/server'; +import { + kibanaResponseFactory, + RequestHandlerContext, + RequestHandler, + SavedObjectsErrorHelpers, +} from '@kbn/core/server'; import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks'; import { getMockedRouterDeps } from '../test_helpers'; @@ -61,7 +66,7 @@ describe('DELETE workpad', () => { }); (mockRouteContext.core.savedObjects.client.delete as jest.Mock).mockImplementationOnce(() => { - throw mockRouteContext.core.savedObjects.client.errors.createBadRequestError('bad request'); + throw SavedObjectsErrorHelpers.createBadRequestError('bad request'); }); const response = await routeHandler( diff --git a/x-pack/plugins/canvas/server/routes/workpad/get.test.ts b/x-pack/plugins/canvas/server/routes/workpad/get.test.ts index 217072d045321..565fdb16f9f30 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/get.test.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/get.test.ts @@ -8,8 +8,8 @@ import { AwaitedProperties } from '@kbn/utility-types'; import { CANVAS_TYPE } from '../../../common/lib/constants'; import { initializeGetWorkpadRoute } from './get'; -import { kibanaResponseFactory, RequestHandler } from '@kbn/core/server'; -import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks'; +import { kibanaResponseFactory, RequestHandler, SavedObjectsErrorHelpers } from '@kbn/core/server'; +import { httpServerMock, coreMock } from '@kbn/core/server/mocks'; import { workpadWithGroupAsElement } from '../../../__fixtures__/workpads'; import { CanvasWorkpad } from '../../../types'; import { getMockedRouterDeps } from '../test_helpers'; @@ -112,9 +112,8 @@ describe('GET workpad', () => { }, }); - const savedObjectsClient = savedObjectsClientMock.create(); mockRouteContext.canvas.workpad.get.mockImplementation(() => { - throw savedObjectsClient.errors.createGenericNotFoundError(CANVAS_TYPE, id); + throw SavedObjectsErrorHelpers.createGenericNotFoundError(CANVAS_TYPE, id); }); const response = await routeHandler( diff --git a/x-pack/plugins/canvas/server/routes/workpad/resolve.test.ts b/x-pack/plugins/canvas/server/routes/workpad/resolve.test.ts index 80fde2fadc18b..e43e30b86dd4d 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/resolve.test.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/resolve.test.ts @@ -8,8 +8,8 @@ import { AwaitedProperties } from '@kbn/utility-types'; import { CANVAS_TYPE } from '../../../common/lib/constants'; import { initializeResolveWorkpadRoute } from './resolve'; -import { kibanaResponseFactory, RequestHandler } from '@kbn/core/server'; -import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks'; +import { kibanaResponseFactory, RequestHandler, SavedObjectsErrorHelpers } from '@kbn/core/server'; +import { httpServerMock, coreMock } from '@kbn/core/server/mocks'; import { workpadWithGroupAsElement } from '../../../__fixtures__/workpads'; import { CanvasWorkpad } from '../../../types'; import { getMockedRouterDeps } from '../test_helpers'; @@ -126,9 +126,8 @@ describe('RESOLVE workpad', () => { }, }); - const savedObjectsClient = savedObjectsClientMock.create(); mockRouteContext.canvas.workpad.resolve.mockImplementation(() => { - throw savedObjectsClient.errors.createGenericNotFoundError(CANVAS_TYPE, id); + throw SavedObjectsErrorHelpers.createGenericNotFoundError(CANVAS_TYPE, id); }); const response = await routeHandler( diff --git a/x-pack/plugins/canvas/server/routes/workpad/update.test.ts b/x-pack/plugins/canvas/server/routes/workpad/update.test.ts index 2467ed56bdc37..2383e7d4beab2 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/update.test.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/update.test.ts @@ -9,7 +9,7 @@ import { AwaitedProperties } from '@kbn/utility-types'; import sinon from 'sinon'; import { CANVAS_TYPE } from '../../../common/lib/constants'; import { initializeUpdateWorkpadRoute, initializeUpdateWorkpadAssetsRoute } from './update'; -import { kibanaResponseFactory, RequestHandler } from '@kbn/core/server'; +import { kibanaResponseFactory, RequestHandler, SavedObjectsErrorHelpers } from '@kbn/core/server'; import { savedObjectsClientMock, httpServerMock, coreMock } from '@kbn/core/server/mocks'; import { workpads } from '../../../__fixtures__/workpads'; import { okResponse } from '../ok_response'; @@ -85,9 +85,7 @@ describe('PUT workpad', () => { }); mockRouteContext.canvas.workpad.update.mockImplementationOnce(() => { - throw mockRouteContext.core.savedObjects.client.errors.createGenericNotFoundError( - 'not found' - ); + throw SavedObjectsErrorHelpers.createGenericNotFoundError('not found'); }); const response = await routeHandler( @@ -110,7 +108,7 @@ describe('PUT workpad', () => { }); mockRouteContext.canvas.workpad.update.mockImplementationOnce(() => { - throw mockRouteContext.core.savedObjects.client.errors.createBadRequestError('bad request'); + throw SavedObjectsErrorHelpers.createBadRequestError('bad request'); }); const response = await routeHandler( diff --git a/x-pack/plugins/infra/server/lib/sources/sources.ts b/x-pack/plugins/infra/server/lib/sources/sources.ts index e24c6ddc46de8..077a0131164e5 100644 --- a/x-pack/plugins/infra/server/lib/sources/sources.ts +++ b/x-pack/plugins/infra/server/lib/sources/sources.ts @@ -10,7 +10,11 @@ import { constant, identity } from 'fp-ts/lib/function'; import { pipe } from 'fp-ts/lib/pipeable'; import { failure } from 'io-ts/lib/PathReporter'; import { inRange } from 'lodash'; -import { SavedObject, SavedObjectsClientContract } from '@kbn/core/server'; +import { + SavedObject, + SavedObjectsClientContract, + SavedObjectsErrorHelpers, +} from '@kbn/core/server'; import { InfraSavedSourceConfiguration, InfraSource, @@ -72,7 +76,7 @@ export class InfraSources { : Promise.reject(err) ) .catch((err) => - savedObjectsClient.errors.isNotFoundError(err) + SavedObjectsErrorHelpers.isNotFoundError(err) ? Promise.resolve({ id: sourceId, version: undefined, diff --git a/x-pack/plugins/infra/server/services/log_views/log_views_client.ts b/x-pack/plugins/infra/server/services/log_views/log_views_client.ts index ef12bcefa233a..57c90235452ba 100644 --- a/x-pack/plugins/infra/server/services/log_views/log_views_client.ts +++ b/x-pack/plugins/infra/server/services/log_views/log_views_client.ts @@ -11,6 +11,7 @@ import { SavedObject, SavedObjectsClientContract, SavedObjectsUtils, + SavedObjectsErrorHelpers, } from '@kbn/core/server'; import { defaultLogViewAttributes, @@ -53,7 +54,7 @@ export class LogViewsClient implements ILogViewsClient { public async getLogView(logViewId: string): Promise { return await this.getSavedLogView(logViewId) .catch((err) => - this.savedObjectsClient.errors.isNotFoundError(err) || err instanceof NotFoundError + SavedObjectsErrorHelpers.isNotFoundError(err) || err instanceof NotFoundError ? this.getInternalLogView(logViewId) : Promise.reject(err) ) From 8ea77f35033861956ca8d932fda72d57a82027ba Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 17:55:12 +0200 Subject: [PATCH 37/46] Am I getting close? --- x-pack/plugins/fleet/server/routes/agent/handlers.ts | 5 ++--- .../fleet/server/routes/enrollment_api_key/handler.ts | 4 ++-- .../fleet/server/services/epm/packages/_install_package.ts | 3 ++- x-pack/plugins/fleet/server/services/epm/packages/remove.ts | 6 +++--- x-pack/plugins/fleet/server/services/package_policy.test.ts | 5 +++-- .../services/preconfiguration/reset_agent_policies.ts | 3 ++- 6 files changed, 14 insertions(+), 12 deletions(-) diff --git a/x-pack/plugins/fleet/server/routes/agent/handlers.ts b/x-pack/plugins/fleet/server/routes/agent/handlers.ts index 42c1ec24f4ee2..564d0a40e9329 100644 --- a/x-pack/plugins/fleet/server/routes/agent/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent/handlers.ts @@ -6,7 +6,7 @@ */ import { uniq } from 'lodash'; -import type { RequestHandler } from '@kbn/core/server'; +import { type RequestHandler, SavedObjectsErrorHelpers } from '@kbn/core/server'; import type { TypeOf } from '@kbn/config-schema'; import type { @@ -35,7 +35,6 @@ export const getAgentHandler: RequestHandler< TypeOf > = async (context, request, response) => { const coreContext = await context.core; - const soClient = coreContext.savedObjects.client; const esClient = coreContext.elasticsearch.client.asInternalUser; try { @@ -45,7 +44,7 @@ export const getAgentHandler: RequestHandler< return response.ok({ body }); } catch (error) { - if (soClient.errors.isNotFoundError(error)) { + if (SavedObjectsErrorHelpers.isNotFoundError(error)) { return response.notFound({ body: { message: `Agent ${request.params.agentId} not found` }, }); diff --git a/x-pack/plugins/fleet/server/routes/enrollment_api_key/handler.ts b/x-pack/plugins/fleet/server/routes/enrollment_api_key/handler.ts index 613bf1ad99be9..d2f38ec06fdd9 100644 --- a/x-pack/plugins/fleet/server/routes/enrollment_api_key/handler.ts +++ b/x-pack/plugins/fleet/server/routes/enrollment_api_key/handler.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { RequestHandler } from '@kbn/core/server'; +import { type RequestHandler, SavedObjectsErrorHelpers } from '@kbn/core/server'; import type { TypeOf } from '@kbn/config-schema'; import type { @@ -61,7 +61,7 @@ export const postEnrollmentApiKeyHandler: RequestHandler< try { // validate policy id await agentPolicyService.get(soClient, request.body.policy_id).catch((err) => { - if (soClient.errors.isNotFoundError(err)) { + if (SavedObjectsErrorHelpers.isNotFoundError(err)) { throw new AgentPolicyNotFoundError(`Agent policy "${request.body.policy_id}" not found`); } diff --git a/x-pack/plugins/fleet/server/services/epm/packages/_install_package.ts b/x-pack/plugins/fleet/server/services/epm/packages/_install_package.ts index ec7e65c2b3875..c8e14575d8009 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/_install_package.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/_install_package.ts @@ -12,6 +12,7 @@ import type { SavedObjectsClientContract, SavedObjectsImporter, } from '@kbn/core/server'; +import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import { MAX_TIME_COMPLETE_INSTALL, @@ -285,7 +286,7 @@ export async function _installPackage({ return [...installedKibanaAssetsRefs, ...esReferences]; } catch (err) { - if (savedObjectsClient.errors.isConflictError(err)) { + if (SavedObjectsErrorHelpers.isConflictError(err)) { throw new ConcurrentInstallOperationError( `Concurrent installation or upgrade of ${pkgName || 'unknown'}-${ pkgVersion || 'unknown' diff --git a/x-pack/plugins/fleet/server/services/epm/packages/remove.ts b/x-pack/plugins/fleet/server/services/epm/packages/remove.ts index 53e001aeee8d0..cf7d95eb34b89 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/remove.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/remove.ts @@ -15,7 +15,7 @@ import { SavedObjectsClient } from '@kbn/core/server'; import { DEFAULT_SPACE_ID } from '@kbn/spaces-plugin/common/constants'; -import { SavedObjectsUtils } from '@kbn/core/server'; +import { SavedObjectsUtils, SavedObjectsErrorHelpers } from '@kbn/core/server'; import { PACKAGE_POLICY_SAVED_OBJECT_TYPE, PACKAGES_SAVED_OBJECT_TYPE } from '../../../constants'; import { ElasticsearchAssetType } from '../../../types'; @@ -176,7 +176,7 @@ async function deleteAssets( ]); } catch (err) { // in the rollback case, partial installs are likely, so missing assets are not an error - if (!savedObjectsClient.errors.isNotFoundError(err)) { + if (!SavedObjectsErrorHelpers.isNotFoundError(err)) { logger.error(err); } } @@ -224,7 +224,7 @@ export async function deleteKibanaSavedObjectsAssets({ await deleteKibanaAssets(assetsToDelete, spaceId); } catch (err) { // in the rollback case, partial installs are likely, so missing assets are not an error - if (!savedObjectsClient.errors.isNotFoundError(err)) { + if (!SavedObjectsErrorHelpers.isNotFoundError(err)) { logger.error(err); } } diff --git a/x-pack/plugins/fleet/server/services/package_policy.test.ts b/x-pack/plugins/fleet/server/services/package_policy.test.ts index c84701bf5d5e9..9fb76a3348750 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.test.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.test.ts @@ -13,11 +13,12 @@ import { } from '@kbn/core/server/mocks'; import { produce } from 'immer'; import type { + KibanaRequest, SavedObjectsClient, SavedObjectsClientContract, SavedObjectsUpdateResponse, } from '@kbn/core/server'; -import type { KibanaRequest } from '@kbn/core/server'; +import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import type { PackageInfo, @@ -620,7 +621,7 @@ describe('Package policy service', () => { _type: string, _id: string ): Promise> => { - throw savedObjectsClient.errors.createConflictError('abc', '123'); + throw SavedObjectsErrorHelpers.createConflictError('abc', '123'); } ); const elasticsearchClient = elasticsearchServiceMock.createClusterClient().asInternalUser; diff --git a/x-pack/plugins/fleet/server/services/preconfiguration/reset_agent_policies.ts b/x-pack/plugins/fleet/server/services/preconfiguration/reset_agent_policies.ts index e4a8fb11ce704..6d456a01d551f 100644 --- a/x-pack/plugins/fleet/server/services/preconfiguration/reset_agent_policies.ts +++ b/x-pack/plugins/fleet/server/services/preconfiguration/reset_agent_policies.ts @@ -7,6 +7,7 @@ import pMap from 'p-map'; import type { ElasticsearchClient, SavedObjectsClientContract, Logger } from '@kbn/core/server'; +import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import { appContextService } from '../app_context'; import { setupFleet } from '../setup'; @@ -105,7 +106,7 @@ async function _deletePreconfigurationDeleteRecord( soClient .delete(PRECONFIGURATION_DELETION_RECORD_SAVED_OBJECT_TYPE, savedObject.id) .catch((err) => { - if (soClient.errors.isNotFoundError(err)) { + if (SavedObjectsErrorHelpers.isNotFoundError(err)) { return undefined; } throw err; From 53de32e81f002a1aaa256fb82c3e3ee402ef8912 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 18:23:14 +0200 Subject: [PATCH 38/46] yet more fixes --- .../lib/artifacts/migrate_artifacts_to_fleet.test.ts | 11 +++-------- .../artifacts/manifest_manager/manifest_manager.ts | 8 ++++++-- .../lib/timeline/saved_object/timelines/index.ts | 9 +++++++-- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/migrate_artifacts_to_fleet.test.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/migrate_artifacts_to_fleet.test.ts index 940acc839b0e7..07a1b0e68d7a9 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/migrate_artifacts_to_fleet.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/migrate_artifacts_to_fleet.test.ts @@ -10,12 +10,7 @@ import { savedObjectsClientMock, elasticsearchServiceMock, } from '@kbn/core/server/mocks'; -import type { - Logger, - SavedObjectsClient, - SavedObjectsFindResponse, - SavedObjectsFindResult, -} from '@kbn/core/server'; +import type { Logger, SavedObjectsFindResponse, SavedObjectsFindResult } from '@kbn/core/server'; import { migrateArtifactsToFleet } from './migrate_artifacts_to_fleet'; import { createEndpointArtifactClientMock } from '../../services/artifacts/mocks'; import type { InternalArtifactCompleteSchema } from '../../schemas'; @@ -24,7 +19,7 @@ import type { NewArtifact } from '@kbn/fleet-plugin/server/services'; import type { CreateRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; describe('When migrating artifacts to fleet', () => { - let soClient: jest.Mocked; + let soClient: ReturnType; let logger: jest.Mocked; let artifactClient: ReturnType; /** An artifact that was created prior to 7.14 */ @@ -44,7 +39,7 @@ describe('When migrating artifacts to fleet', () => { }; beforeEach(async () => { - soClient = savedObjectsClientMock.create() as jest.Mocked; + soClient = savedObjectsClientMock.create(); logger = loggingSystemMock.create().get() as jest.Mocked; artifactClient = createEndpointArtifactClientMock(); // pre-v7.14 artifact, which is compressed diff --git a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.ts b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.ts index a843a6d325f6e..bd85bdc723ce2 100644 --- a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.ts +++ b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.ts @@ -9,7 +9,11 @@ import pMap from 'p-map'; import semver from 'semver'; import type LRU from 'lru-cache'; import { isEqual, isEmpty } from 'lodash'; -import type { Logger, SavedObjectsClientContract } from '@kbn/core/server'; +import { + type Logger, + type SavedObjectsClientContract, + SavedObjectsErrorHelpers, +} from '@kbn/core/server'; import { ENDPOINT_EVENT_FILTERS_LIST_ID, ENDPOINT_TRUSTED_APPS_LIST_ID, @@ -348,7 +352,7 @@ export class ManifestManager { // Cache the compressed body of the artifact this.cache.set(artifactId, Buffer.from(artifact.body, 'base64')); } catch (err) { - if (this.savedObjectsClient.errors.isConflictError(err)) { + if (SavedObjectsErrorHelpers.isConflictError(err)) { this.logger.debug(`Tried to create artifact ${artifactId}, but it already exists.`); } else { return [err, undefined]; diff --git a/x-pack/plugins/security_solution/server/lib/timeline/saved_object/timelines/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/saved_object/timelines/index.ts index a7c09062094e1..957a6c95d16d9 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/saved_object/timelines/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/saved_object/timelines/index.ts @@ -7,7 +7,11 @@ import { getOr } from 'lodash/fp'; -import type { SavedObjectsClientContract, SavedObjectsFindOptions } from '@kbn/core/server'; +import { + type SavedObjectsClientContract, + type SavedObjectsFindOptions, + SavedObjectsErrorHelpers, +} from '@kbn/core/server'; import type { AuthenticatedUser } from '@kbn/security-plugin/server'; import { UNAUTHENTICATED_USER } from '../../../../../common/constants'; import type { NoteSavedObject } from '../../../../../common/types/timeline/note'; @@ -38,6 +42,7 @@ import { timelineSavedObjectType } from '../../saved_object_mappings'; import { draftTimelineDefaults } from '../../utils/default_timeline'; import type { Maybe } from '../../../../../common/search_strategy'; import { timelineFieldsMigrator } from './field_migrator'; + export { pickSavedTimeline } from './pick_saved_timeline'; export { convertSavedObjectToSavedTimeline } from './convert_saved_object_to_savedtimeline'; @@ -395,7 +400,7 @@ export const persistTimeline = async ( version, }); } catch (err) { - if (timelineId != null && savedObjectsClient.errors.isConflictError(err)) { + if (timelineId != null && SavedObjectsErrorHelpers.isConflictError(err)) { return { code: 409, message: err.message, From a4e554fcfcddce42e336afb12f957586a0eb9916 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 18:27:18 +0200 Subject: [PATCH 39/46] back to client impl --- .../lib/artifacts/migrate_artifacts_to_fleet.test.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/migrate_artifacts_to_fleet.test.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/migrate_artifacts_to_fleet.test.ts index 07a1b0e68d7a9..277772253b92e 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/migrate_artifacts_to_fleet.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/migrate_artifacts_to_fleet.test.ts @@ -10,7 +10,12 @@ import { savedObjectsClientMock, elasticsearchServiceMock, } from '@kbn/core/server/mocks'; -import type { Logger, SavedObjectsFindResponse, SavedObjectsFindResult } from '@kbn/core/server'; +import type { + SavedObjectsClient, + Logger, + SavedObjectsFindResponse, + SavedObjectsFindResult, +} from '@kbn/core/server'; import { migrateArtifactsToFleet } from './migrate_artifacts_to_fleet'; import { createEndpointArtifactClientMock } from '../../services/artifacts/mocks'; import type { InternalArtifactCompleteSchema } from '../../schemas'; @@ -19,7 +24,7 @@ import type { NewArtifact } from '@kbn/fleet-plugin/server/services'; import type { CreateRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; describe('When migrating artifacts to fleet', () => { - let soClient: ReturnType; + let soClient: jest.Mocked; let logger: jest.Mocked; let artifactClient: ReturnType; /** An artifact that was created prior to 7.14 */ @@ -39,7 +44,7 @@ describe('When migrating artifacts to fleet', () => { }; beforeEach(async () => { - soClient = savedObjectsClientMock.create(); + soClient = savedObjectsClientMock.create() as unknown as jest.Mocked; logger = loggingSystemMock.create().get() as jest.Mocked; artifactClient = createEndpointArtifactClientMock(); // pre-v7.14 artifact, which is compressed From 51435a0d0db76ad1b637455157a3cb1ae885076a Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 19:32:16 +0200 Subject: [PATCH 40/46] fix bulkGetting undefined --- .../server/lib/timeline/saved_object/timelines/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/plugins/security_solution/server/lib/timeline/saved_object/timelines/index.ts b/x-pack/plugins/security_solution/server/lib/timeline/saved_object/timelines/index.ts index 957a6c95d16d9..0a7201203126d 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/saved_object/timelines/index.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/saved_object/timelines/index.ts @@ -717,7 +717,7 @@ export const getSelectedTimelines = async ( const savedObjects = await Promise.resolve( savedObjectsClient.bulkGet( - exportedIds?.reduce( + (exportedIds ?? []).reduce( (acc, timelineId) => [...acc, { id: timelineId, type: timelineSavedObjectType }], [] as Array<{ id: string; type: string }> ) From f98fffbe641d4ab7f87472ee28968344b11ace9b Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Thu, 21 Jul 2022 20:14:18 +0200 Subject: [PATCH 41/46] fix SS mock --- x-pack/plugins/security_solution/server/__mocks__/core.mock.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/x-pack/plugins/security_solution/server/__mocks__/core.mock.ts b/x-pack/plugins/security_solution/server/__mocks__/core.mock.ts index adf7a0a8eb193..47703d54ec3b8 100644 --- a/x-pack/plugins/security_solution/server/__mocks__/core.mock.ts +++ b/x-pack/plugins/security_solution/server/__mocks__/core.mock.ts @@ -10,6 +10,9 @@ // We _must_ import from the restricted path or we pull in _everything_ including memory leaks from Kibana core // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { SavedObjectsUtils } from '@kbn/core/server/saved_objects/service/lib/utils'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { SavedObjectsErrorHelpers } from '@kbn/core/server/saved_objects/service/lib/errors'; module.exports = { SavedObjectsUtils, + SavedObjectsErrorHelpers, }; From 252159e154dba96ec49bac3a869532a051b9b522 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Fri, 22 Jul 2022 08:01:22 +0200 Subject: [PATCH 42/46] some cleanup --- .../core-saved-objects-common/BUILD.bazel | 22 +------------------ .../core-saved-objects-common/README.md | 2 +- .../core-saved-objects-common/src/types.ts | 2 ++ .../core-saved-objects-common/tsconfig.json | 3 +-- 4 files changed, 5 insertions(+), 24 deletions(-) diff --git a/packages/core/saved-objects/core-saved-objects-common/BUILD.bazel b/packages/core/saved-objects/core-saved-objects-common/BUILD.bazel index 4d321f1c92412..a83830f79b345 100644 --- a/packages/core/saved-objects/core-saved-objects-common/BUILD.bazel +++ b/packages/core/saved-objects/core-saved-objects-common/BUILD.bazel @@ -27,33 +27,13 @@ NPM_MODULE_EXTRA_FILES = [ "package.json", ] -# In this array place runtime dependencies, including other packages and NPM packages -# which must be available for this code to run. -# -# To reference other packages use: -# "//repo/relative/path/to/package" -# eg. "//packages/kbn-utils" -# -# To reference a NPM package use: -# "@npm//name-of-package" -# eg. "@npm//lodash" RUNTIME_DEPS = [ "@npm//react" ] -# In this array place dependencies necessary to build the types, which will include the -# :npm_module_types target of other packages and packages from NPM, including @types/* -# packages. -# -# To reference the types for another package use: -# "//repo/relative/path/to/package:npm_module_types" -# eg. "//packages/kbn-utils:npm_module_types" -# -# References to NPM packages work the same as RUNTIME_DEPS TYPES_DEPS = [ "@npm//@types/node", - "@npm//@types/jest", - "@npm//@types/react" + "@npm//@types/jest" ] jsts_transpiler( diff --git a/packages/core/saved-objects/core-saved-objects-common/README.md b/packages/core/saved-objects/core-saved-objects-common/README.md index 3619e2b4cf8bb..3c0632ee6d57e 100644 --- a/packages/core/saved-objects/core-saved-objects-common/README.md +++ b/packages/core/saved-objects/core-saved-objects-common/README.md @@ -1,3 +1,3 @@ # @kbn/core-saved-objects-common -Empty package generated by @kbn/generate +This package contains the common types shared between the browser and server-side savedObjets APIs. diff --git a/packages/core/saved-objects/core-saved-objects-common/src/types.ts b/packages/core/saved-objects/core-saved-objects-common/src/types.ts index 78992162fc610..102de1a4cfbb6 100644 --- a/packages/core/saved-objects/core-saved-objects-common/src/types.ts +++ b/packages/core/saved-objects/core-saved-objects-common/src/types.ts @@ -7,6 +7,8 @@ */ /** + * An identifier for a saved object within a space. + * * @public */ export interface SavedObjectTypeIdTuple { diff --git a/packages/core/saved-objects/core-saved-objects-common/tsconfig.json b/packages/core/saved-objects/core-saved-objects-common/tsconfig.json index d10eb479b3697..39d3c7097814a 100644 --- a/packages/core/saved-objects/core-saved-objects-common/tsconfig.json +++ b/packages/core/saved-objects/core-saved-objects-common/tsconfig.json @@ -9,8 +9,7 @@ "stripInternal": false, "types": [ "jest", - "node", - "react" + "node" ] }, "include": [ From 3aacfd587f0f05e965669d47911e431e2bd5393a Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Fri, 22 Jul 2022 09:32:08 +0200 Subject: [PATCH 43/46] self-review --- .../saved_objects/import/import_saved_objects.ts | 2 +- .../saved_objects/import/lib/check_conflicts.test.ts | 2 +- .../import/lib/check_origin_conflicts.test.ts | 2 +- .../saved_objects/import/lib/check_origin_conflicts.ts | 2 +- .../import/lib/create_saved_objects.test.ts | 2 +- .../saved_objects/import/lib/create_saved_objects.ts | 2 +- .../import/lib/get_import_state_map_for_retries.ts | 2 +- .../saved_objects/import/lib/validate_references.ts | 2 +- .../saved_objects/import/resolve_import_errors.test.ts | 3 ++- .../saved_objects/import/resolve_import_errors.ts | 2 +- src/core/server/saved_objects/serialization/types.ts | 5 ++++- .../discover/public/services/saved_searches/types.ts | 8 ++++---- .../graph/public/helpers/use_workspace_loader.ts | 10 +++++----- x-pack/plugins/spaces/public/legacy_urls/types.ts | 4 ++-- 14 files changed, 26 insertions(+), 22 deletions(-) diff --git a/src/core/server/saved_objects/import/import_saved_objects.ts b/src/core/server/saved_objects/import/import_saved_objects.ts index ea9f14de6506c..504dd8ef9396e 100644 --- a/src/core/server/saved_objects/import/import_saved_objects.ts +++ b/src/core/server/saved_objects/import/import_saved_objects.ts @@ -11,8 +11,8 @@ import type { SavedObjectsImportFailure, SavedObjectsImportResponse, } from '@kbn/core-saved-objects-common'; +import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry'; -import { SavedObjectsClientContract } from '../types'; import { SavedObjectsImportHook } from './types'; import { checkReferenceOrigins, diff --git a/src/core/server/saved_objects/import/lib/check_conflicts.test.ts b/src/core/server/saved_objects/import/lib/check_conflicts.test.ts index e78e438cd3a2d..3dcbeacae1a2d 100644 --- a/src/core/server/saved_objects/import/lib/check_conflicts.test.ts +++ b/src/core/server/saved_objects/import/lib/check_conflicts.test.ts @@ -12,7 +12,7 @@ import type { SavedObjectReference, SavedObjectsImportRetry, } from '@kbn/core-saved-objects-common'; -import { SavedObjectsClientContract } from '../../types'; +import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; import { SavedObjectsErrorHelpers } from '../../service'; import { checkConflicts } from './check_conflicts'; diff --git a/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts b/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts index 9d85f4a563035..2d75fdfb73116 100644 --- a/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts +++ b/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts @@ -14,7 +14,7 @@ import type { SavedObjectsImportFailure, SavedObjectsImportRetry, } from '@kbn/core-saved-objects-common'; -import { SavedObjectsClientContract } from '../../types'; +import { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; import { checkOriginConflicts } from './check_origin_conflicts'; import { savedObjectsClientMock } from '../../../mocks'; import { typeRegistryMock } from '../../saved_objects_type_registry.mock'; diff --git a/src/core/server/saved_objects/import/lib/check_origin_conflicts.ts b/src/core/server/saved_objects/import/lib/check_origin_conflicts.ts index 71dbe6bcbc4d0..bd22d50841a52 100644 --- a/src/core/server/saved_objects/import/lib/check_origin_conflicts.ts +++ b/src/core/server/saved_objects/import/lib/check_origin_conflicts.ts @@ -13,7 +13,7 @@ import type { SavedObjectsImportFailure, SavedObjectsImportRetry, } from '@kbn/core-saved-objects-common'; -import type { SavedObjectsClientContract } from '../../types'; +import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; import { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import { getObjectKey } from '../../service/lib/internal_utils'; import type { ImportStateMap } from './types'; diff --git a/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts b/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts index 88ce8ce3b6886..a29765849c364 100644 --- a/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts +++ b/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts @@ -8,8 +8,8 @@ import { savedObjectsClientMock } from '../../../mocks'; import type { SavedObject, SavedObjectsImportFailure } from '@kbn/core-saved-objects-common'; +import { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; import { createSavedObjects } from './create_saved_objects'; -import { SavedObjectsClientContract } from '../../types'; import { SavedObjectsErrorHelpers } from '../../service'; import { extractErrors } from './extract_errors'; diff --git a/src/core/server/saved_objects/import/lib/create_saved_objects.ts b/src/core/server/saved_objects/import/lib/create_saved_objects.ts index 6423f793418b3..95affbd61097b 100644 --- a/src/core/server/saved_objects/import/lib/create_saved_objects.ts +++ b/src/core/server/saved_objects/import/lib/create_saved_objects.ts @@ -7,7 +7,7 @@ */ import type { SavedObject, SavedObjectsImportFailure } from '@kbn/core-saved-objects-common'; -import { SavedObjectsClientContract } from '../../types'; +import { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; import { extractErrors } from './extract_errors'; import { CreatedObject } from '../types'; import type { ImportStateMap } from './types'; diff --git a/src/core/server/saved_objects/import/lib/get_import_state_map_for_retries.ts b/src/core/server/saved_objects/import/lib/get_import_state_map_for_retries.ts index 43a6730f33550..dd4ed3036fb8c 100644 --- a/src/core/server/saved_objects/import/lib/get_import_state_map_for_retries.ts +++ b/src/core/server/saved_objects/import/lib/get_import_state_map_for_retries.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import { SavedObject, SavedObjectsImportRetry } from '@kbn/core-saved-objects-common'; +import type { SavedObject, SavedObjectsImportRetry } from '@kbn/core-saved-objects-common'; import type { ImportStateMap } from './types'; interface GetImportStateMapForRetriesParams { diff --git a/src/core/server/saved_objects/import/lib/validate_references.ts b/src/core/server/saved_objects/import/lib/validate_references.ts index 9d9c92ec4a625..8f271908bf48d 100644 --- a/src/core/server/saved_objects/import/lib/validate_references.ts +++ b/src/core/server/saved_objects/import/lib/validate_references.ts @@ -11,7 +11,7 @@ import type { SavedObjectsImportFailure, SavedObjectsImportRetry, } from '@kbn/core-saved-objects-common'; -import { SavedObjectsClientContract } from '../../types'; +import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; import { SavedObjectsImportError } from '../errors'; import type { ImportStateMap } from './types'; diff --git a/src/core/server/saved_objects/import/resolve_import_errors.test.ts b/src/core/server/saved_objects/import/resolve_import_errors.test.ts index 08608978fecaa..5a2f91e10ac6f 100644 --- a/src/core/server/saved_objects/import/resolve_import_errors.test.ts +++ b/src/core/server/saved_objects/import/resolve_import_errors.test.ts @@ -30,7 +30,8 @@ import type { SavedObjectReference, SavedObjectsImportWarning, } from '@kbn/core-saved-objects-common'; -import { SavedObjectsClientContract, SavedObjectsType } from '../types'; +import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; +import { SavedObjectsType } from '../types'; import { savedObjectsClientMock } from '../../mocks'; import { ISavedObjectTypeRegistry, SavedObjectsImportHook } from '..'; import { typeRegistryMock } from '../saved_objects_type_registry.mock'; diff --git a/src/core/server/saved_objects/import/resolve_import_errors.ts b/src/core/server/saved_objects/import/resolve_import_errors.ts index b9919ff1aa81c..21e7eaee0cf36 100644 --- a/src/core/server/saved_objects/import/resolve_import_errors.ts +++ b/src/core/server/saved_objects/import/resolve_import_errors.ts @@ -14,7 +14,7 @@ import type { SavedObjectsImportResponse, SavedObjectsImportSuccess, } from '@kbn/core-saved-objects-common'; -import { SavedObjectsClientContract } from '../types'; +import type { SavedObjectsClientContract } from '@kbn/core-saved-objects-api-server'; import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry'; import { SavedObjectsImportHook } from './types'; import { diff --git a/src/core/server/saved_objects/serialization/types.ts b/src/core/server/saved_objects/serialization/types.ts index 72def2def3e43..4c6fa73065cf7 100644 --- a/src/core/server/saved_objects/serialization/types.ts +++ b/src/core/server/saved_objects/serialization/types.ts @@ -6,7 +6,10 @@ * Side Public License, v 1. */ -import { SavedObjectsMigrationVersion, SavedObjectReference } from '@kbn/core-saved-objects-common'; +import type { + SavedObjectsMigrationVersion, + SavedObjectReference, +} from '@kbn/core-saved-objects-common'; /** * A raw document as represented directly in the saved object index. diff --git a/src/plugins/discover/public/services/saved_searches/types.ts b/src/plugins/discover/public/services/saved_searches/types.ts index 8cdf18616f356..ef3387943d89c 100644 --- a/src/plugins/discover/public/services/saved_searches/types.ts +++ b/src/plugins/discover/public/services/saved_searches/types.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import type { SavedObjectsResolveResponse } from '@kbn/core-saved-objects-api-server'; +import type { ResolvedSimpleSavedObject } from '@kbn/core/public'; import type { ISearchSource } from '@kbn/data-plugin/public'; import { DiscoverGridSettingsColumn } from '../../components/discover_grid/types'; import { VIEW_MODE } from '../../components/view_mode_toggle'; @@ -46,9 +46,9 @@ export interface SavedSearch { }; hideChart?: boolean; sharingSavedObjectProps?: { - outcome?: SavedObjectsResolveResponse['outcome']; - aliasTargetId?: SavedObjectsResolveResponse['alias_target_id']; - aliasPurpose?: SavedObjectsResolveResponse['alias_purpose']; + outcome?: ResolvedSimpleSavedObject['outcome']; + aliasTargetId?: ResolvedSimpleSavedObject['alias_target_id']; + aliasPurpose?: ResolvedSimpleSavedObject['alias_purpose']; errorJSON?: string; }; viewMode?: VIEW_MODE; diff --git a/x-pack/plugins/graph/public/helpers/use_workspace_loader.ts b/x-pack/plugins/graph/public/helpers/use_workspace_loader.ts index d878f001f2984..8c0a7f38fdea2 100644 --- a/x-pack/plugins/graph/public/helpers/use_workspace_loader.ts +++ b/x-pack/plugins/graph/public/helpers/use_workspace_loader.ts @@ -7,8 +7,7 @@ import { useEffect, useState } from 'react'; import { useHistory, useLocation, useParams } from 'react-router-dom'; -import type { SavedObjectsClientContract } from '@kbn/core/public'; -import type { SavedObjectsResolveResponse } from '@kbn/core-saved-objects-api-server'; +import type { SavedObjectsClientContract, ResolvedSimpleSavedObject } from '@kbn/core/public'; import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; import { i18n } from '@kbn/i18n'; import { CoreStart } from '@kbn/core/public'; @@ -31,10 +30,11 @@ export interface UseWorkspaceLoaderProps { interface WorkspaceUrlParams { id?: string; } + export interface SharingSavedObjectProps { - outcome?: SavedObjectsResolveResponse['outcome']; - aliasTargetId?: SavedObjectsResolveResponse['alias_target_id']; - aliasPurpose?: SavedObjectsResolveResponse['alias_purpose']; + outcome?: ResolvedSimpleSavedObject['outcome']; + aliasTargetId?: ResolvedSimpleSavedObject['alias_target_id']; + aliasPurpose?: ResolvedSimpleSavedObject['alias_purpose']; } interface WorkspaceLoadedState { diff --git a/x-pack/plugins/spaces/public/legacy_urls/types.ts b/x-pack/plugins/spaces/public/legacy_urls/types.ts index 7ad3919d9d166..7fb1a768a1aac 100644 --- a/x-pack/plugins/spaces/public/legacy_urls/types.ts +++ b/x-pack/plugins/spaces/public/legacy_urls/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { SavedObjectsResolveResponse } from '@kbn/core-saved-objects-api-server'; +import type { ResolvedSimpleSavedObject } from '@kbn/core/public'; /** * Properties for the LegacyUrlConflict component. @@ -61,7 +61,7 @@ export interface RedirectLegacyUrlParams { * This is used to determine whether or not a toast should be shown when a user is redirected from a legacy URL; if the alias was created * because of saved object conversion, then we will display a toast telling the user that the object has a new URL. */ - aliasPurpose: SavedObjectsResolveResponse['alias_purpose']; + aliasPurpose: ResolvedSimpleSavedObject['alias_purpose']; /** * The string that is used to describe the object in the toast, e.g., _The **object** you're looking for has a new location_. * Default value is 'object'. From 42caa2433b6b525c6e7c0b9460673e02b0e96ba8 Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Mon, 25 Jul 2022 09:52:21 +0200 Subject: [PATCH 44/46] fix new usages --- x-pack/plugins/osquery/public/packs/use_packs.ts | 4 ++-- .../plugins/osquery/public/saved_queries/use_saved_queries.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/osquery/public/packs/use_packs.ts b/x-pack/plugins/osquery/public/packs/use_packs.ts index 27c7dc9250783..b8fadaf571a84 100644 --- a/x-pack/plugins/osquery/public/packs/use_packs.ts +++ b/x-pack/plugins/osquery/public/packs/use_packs.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { SavedObjectsFindResponsePublic } from '@kbn/core/public'; +import type { SavedObjectsFindResponse } from '@kbn/core/public'; import { useQuery } from 'react-query'; import { useKibana } from '../common/lib/kibana'; @@ -22,7 +22,7 @@ export const usePacks = ({ const { http } = useKibana().services; return useQuery< - Omit & { + Omit & { data: PackSavedObject[]; } >( diff --git a/x-pack/plugins/osquery/public/saved_queries/use_saved_queries.ts b/x-pack/plugins/osquery/public/saved_queries/use_saved_queries.ts index acc08d5a2ceb6..53d07c52e325b 100644 --- a/x-pack/plugins/osquery/public/saved_queries/use_saved_queries.ts +++ b/x-pack/plugins/osquery/public/saved_queries/use_saved_queries.ts @@ -7,7 +7,7 @@ import { useQuery } from 'react-query'; -import type { SavedObjectsFindResponsePublic } from '@kbn/core/public'; +import type { SavedObjectsFindResponse } from '@kbn/core/public'; import { useKibana } from '../common/lib/kibana'; import { useErrorToast } from '../common/hooks/use_error_toast'; import { SAVED_QUERIES_ID } from './constants'; @@ -24,7 +24,7 @@ export const useSavedQueries = ({ const setErrorToast = useErrorToast(); return useQuery< - Omit & { + Omit & { data: SavedQuerySO[]; }, { body: { error: string; message: string } } From b81bb0b730d6c39249ed3d0950d59c299652cfce Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 26 Jul 2022 09:09:17 +0200 Subject: [PATCH 45/46] fix typo --- packages/core/saved-objects/core-saved-objects-common/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/saved-objects/core-saved-objects-common/README.md b/packages/core/saved-objects/core-saved-objects-common/README.md index 3c0632ee6d57e..98319ddf05071 100644 --- a/packages/core/saved-objects/core-saved-objects-common/README.md +++ b/packages/core/saved-objects/core-saved-objects-common/README.md @@ -1,3 +1,3 @@ # @kbn/core-saved-objects-common -This package contains the common types shared between the browser and server-side savedObjets APIs. +This package contains the common types shared between the browser and server-side savedObjects APIs. From 0650e7a1efd9ea8481bbad567cde92f89c6938fe Mon Sep 17 00:00:00 2001 From: pgayvallet Date: Tue, 26 Jul 2022 11:36:23 +0200 Subject: [PATCH 46/46] fix new usage --- x-pack/plugins/fleet/server/services/package_policy.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/fleet/server/services/package_policy.ts b/x-pack/plugins/fleet/server/services/package_policy.ts index 3164d417a6455..ecdff37854b27 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.ts @@ -9,8 +9,9 @@ import { omit, partition, isEqual } from 'lodash'; import { i18n } from '@kbn/i18n'; import semverLt from 'semver/functions/lt'; import { getFlattenedObject } from '@kbn/std'; -import type { KibanaRequest } from '@kbn/core/server'; +import { SavedObjectsErrorHelpers } from '@kbn/core/server'; import type { + KibanaRequest, ElasticsearchClient, RequestHandlerContext, SavedObjectsClientContract, @@ -487,7 +488,7 @@ class PackagePolicyService implements PackagePolicyServiceInterface { const agentPolicy = await agentPolicyService .get(soClient, packagePolicy.policy_id) .catch((err) => { - if (soClient.errors.isNotFoundError(err)) { + if (SavedObjectsErrorHelpers.isNotFoundError(err)) { appContextService .getLogger() .warn(`Agent policy ${packagePolicy.policy_id} not found`); @@ -1343,6 +1344,7 @@ export interface PackagePolicyServiceInterface { id: string ): Promise<{ packagePolicy: PackagePolicy; packageInfo: PackageInfo }>; } + export const packagePolicyService: PackagePolicyServiceInterface = new PackagePolicyService(); export type { PackagePolicyService };