Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[Backport 2.x] [Workspace]feat: enable maximum workspaces #9249

Merged
merged 1 commit into from
Jan 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelogs/fragments/9226.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
feat:
- Enable maximum workspaces ([#9226](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/9226))
4 changes: 4 additions & 0 deletions config/opensearch_dashboards.yml
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,10 @@
# overrides:
# "home:useNewHomePage": true

# Set a maximum number of workspaces
# by default, there is no limit.
# workspace.maximum_workspaces: 100

# Optional settings to specify saved object types to be deleted during migration.
# This feature can help address compatibility issues that may arise during the migration of saved objects, such as types defined by legacy applications.
# Please note, using this feature carries a risk. Deleting saved objects during migration could potentially lead to unintended data loss. Use with caution.
Expand Down
1 change: 1 addition & 0 deletions src/plugins/workspace/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { schema, TypeOf } from '@osd/config-schema';

export const configSchema = schema.object({
enabled: schema.boolean({ defaultValue: false }),
maximum_workspaces: schema.maybe(schema.number()),
});

export type ConfigSchema = TypeOf<typeof configSchema>;
8 changes: 7 additions & 1 deletion src/plugins/workspace/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import { WorkspaceUiSettingsClientWrapper } from './saved_objects/workspace_ui_s
import { uiSettings } from './ui_settings';
import { RepositoryWrapper } from './saved_objects/repository_wrapper';
import { DataSourcePluginSetup } from '../../data_source/server';
import { ConfigSchema } from '../config';

export interface WorkspacePluginDependencies {
dataSource: DataSourcePluginSetup;
Expand All @@ -68,6 +69,7 @@ export class WorkspacePlugin implements Plugin<WorkspacePluginSetup, WorkspacePl
private readonly globalConfig$: Observable<SharedGlobalConfig>;
private workspaceSavedObjectsClientWrapper?: WorkspaceSavedObjectsClientWrapper;
private workspaceUiSettingsClientWrapper?: WorkspaceUiSettingsClientWrapper;
private workspaceConfig$: Observable<ConfigSchema>;

private proxyWorkspaceTrafficToRealHandler(setupDeps: CoreSetup) {
/**
Expand Down Expand Up @@ -215,18 +217,22 @@ export class WorkspacePlugin implements Plugin<WorkspacePluginSetup, WorkspacePl
constructor(initializerContext: PluginInitializerContext) {
this.logger = initializerContext.logger.get();
this.globalConfig$ = initializerContext.config.legacy.globalConfig$;
this.workspaceConfig$ = initializerContext.config.create();
}

public async setup(core: CoreSetup, deps: WorkspacePluginDependencies) {
this.logger.debug('Setting up Workspaces service');
const globalConfig = await this.globalConfig$.pipe(first()).toPromise();
const workspaceConfig = await this.workspaceConfig$.pipe(first()).toPromise();
const isPermissionControlEnabled = globalConfig.savedObjects.permission.enabled === true;
const isDataSourceEnabled = !!deps.dataSource;

// setup new ui_setting user's default workspace
core.uiSettings.register(uiSettings);

this.client = new WorkspaceClient(core, this.logger);
this.client = new WorkspaceClient(core, this.logger, {
maximum_workspaces: workspaceConfig.maximum_workspaces,
});

await this.client.setup(core);

Expand Down
41 changes: 39 additions & 2 deletions src/plugins/workspace/server/workspace_client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ import {
DATA_SOURCE_SAVED_OBJECT_TYPE,
DATA_CONNECTION_SAVED_OBJECT_TYPE,
} from '../../data_source/common';
import { SavedObjectsServiceStart, SavedObjectsClientContract } from '../../../core/server';
import {
SavedObjectsServiceStart,
SavedObjectsClientContract,
IUiSettingsClient,
} from '../../../core/server';
import { IRequestDetail } from './types';

const coreSetup = coreMock.createSetup();
Expand All @@ -33,7 +37,8 @@ jest.mock('./utils', () => ({
{ type: 'data-connection', id: 'id1' },
{ type: 'data-connection', id: 'id2' },
]),
checkAndSetDefaultDataSource: (...args) => mockCheckAndSetDefaultDataSource(...args),
checkAndSetDefaultDataSource: (...args: [IUiSettingsClient, string[], boolean]) =>
mockCheckAndSetDefaultDataSource(...args),
}));

describe('#WorkspaceClient', () => {
Expand Down Expand Up @@ -125,6 +130,38 @@ describe('#WorkspaceClient', () => {
);
});

it('create# should call find when maximum workspaces are set', async () => {
const client = new WorkspaceClient(coreSetup, logger, {
maximum_workspaces: 1,
});
client?.setSavedObjects(savedObjects);

find.mockImplementation((findParams) => {
if (!findParams.search) {
return {
total: 1,
};
}

return {};
});

const createResult = await client.create(mockRequestDetail, {
name: mockWorkspaceName,
permissions: {},
dataSources: [],
dataConnections: [],
});

expect(createResult).toEqual({
success: false,
error: 'Maximum number of workspaces (1) reached',
});

expect(find).toHaveBeenCalledTimes(2);
find.mockClear();
});

it('update# should not call addToWorkspaces if no new data sources and data connections added', async () => {
const client = new WorkspaceClient(coreSetup, logger);
await client.setup(coreSetup);
Expand Down
38 changes: 30 additions & 8 deletions src/plugins/workspace/server/workspace_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
DATA_SOURCE_SAVED_OBJECT_TYPE,
DATA_CONNECTION_SAVED_OBJECT_TYPE,
} from '../../data_source/common';
import { ConfigSchema } from '../config';

const WORKSPACE_ID_SIZE = 6;

Expand All @@ -44,15 +45,21 @@ const WORKSPACE_NOT_FOUND_ERROR = i18n.translate('workspace.notFound.error', {
defaultMessage: 'workspace not found',
});

interface ConfigType {
maximum_workspaces?: ConfigSchema['maximum_workspaces'];
}

export class WorkspaceClient implements IWorkspaceClientImpl {
private setupDep: CoreSetup;
private logger: Logger;
private savedObjects?: SavedObjectsServiceStart;
private uiSettings?: UiSettingsServiceStart;
private config?: ConfigType;

constructor(core: CoreSetup, logger: Logger) {
constructor(core: CoreSetup, logger: Logger, config?: ConfigType) {
this.setupDep = core;
this.logger = logger;
this.config = config;
}

private getScopedClientWithoutPermission(
Expand Down Expand Up @@ -115,17 +122,32 @@ export class WorkspaceClient implements IWorkspaceClientImpl {
const { permissions, dataSources, dataConnections, ...attributes } = payload;
const id = generateRandomId(WORKSPACE_ID_SIZE);
const client = this.getSavedObjectClientsFromRequestDetail(requestDetail);
const existingWorkspaceRes = await this.getScopedClientWithoutPermission(requestDetail)?.find(
{
type: WORKSPACE_TYPE,
search: `"${attributes.name}"`,
searchFields: ['name'],
}
);
const clientWithoutPermission = this.getScopedClientWithoutPermission(requestDetail);
const existingWorkspaceRes = await clientWithoutPermission?.find({
type: WORKSPACE_TYPE,
search: `"${attributes.name}"`,
searchFields: ['name'],
});
if (existingWorkspaceRes && existingWorkspaceRes.total > 0) {
throw new Error(DUPLICATE_WORKSPACE_NAME_ERROR);
}

if (this.config?.maximum_workspaces) {
const workspaces = await clientWithoutPermission?.find({
type: WORKSPACE_TYPE,
});
if (workspaces && workspaces.total >= this.config.maximum_workspaces) {
throw new Error(
i18n.translate('workspace.maximum.error', {
defaultMessage: 'Maximum number of workspaces ({length}) reached',
values: {
length: this.config.maximum_workspaces,
},
})
);
}
}

const promises = [];

if (dataSources) {
Expand Down
Loading