Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 56 additions & 1 deletion packages/backend/src/studio-api-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,19 @@ import type { RecipePullOptions } from '@shared/src/models/IRecipe';
import type { ContainerProviderConnection } from '@podman-desktop/api';
import type { NavigationRegistry } from './registries/NavigationRegistry';
import type { FilterRecipesResult, RecipeFilters } from '@shared/src/models/FilterRecipesResult';
import type { ErrorState } from '@shared/src/models/IError';
import type { ServiceMetadata } from '@shared/src/models/ServiceMetadata';
import { Messages } from '@shared/Messages';
import type { RpcBrowser } from '@shared/src/messages/MessageProxy';

interface PortQuickPickItem extends podmanDesktopApi.QuickPickItem {
port: number;
}

export class StudioApiImpl implements StudioAPI {
#errors: ErrorState[] = [];
#rpcBrowser: RpcBrowser | undefined;

constructor(
private applicationManager: ApplicationManager,
private catalogManager: CatalogManager,
Expand All @@ -78,7 +85,55 @@ export class StudioApiImpl implements StudioAPI {
private recipeManager: RecipeManager,
private podmanConnection: PodmanConnection,
private navigationRegistry: NavigationRegistry,
) {}
rpcBrowser?: RpcBrowser,
) {
this.#rpcBrowser = rpcBrowser;
}

async getErrors(): Promise<ErrorState[]> {
return this.#errors;
}

async acknowledgeError(errorId: string): Promise<void> {
const error = this.#errors.find(e => e.id === errorId);
if (error) {
error.acknowledged = true;
// Notify subscribers of the updated error state
this.notify(Messages.MSG_NEW_ERROR_STATE, this.#errors);
}
}

async resolveServiceUri(uri: string): Promise<ServiceMetadata> {
// Basic validation of MCP URI format
if (!uri.startsWith('mcp://')) {
throw new Error('Invalid MCP URI format. Must start with mcp://');
}

// For now return empty metadata - this can be expanded based on requirements
return {};
}

// Helper method to create and track errors
async createError(error: Omit<ErrorState, 'id' | 'timestamp'>): Promise<void> {
const newError: ErrorState = {
...error,
id: crypto.randomUUID(),
timestamp: Date.now(),
};
this.#errors.push(newError);
// Notify subscribers of the new error state
this.notify(Messages.MSG_NEW_ERROR_STATE, this.#errors);
}

private notify(channel: string, message: unknown): void {
if (this.#rpcBrowser) {
// Use the RpcBrowser's subscribe mechanism to notify subscribers
const subscribers = this.#rpcBrowser.subscribers.get(channel);
if (subscribers) {
subscribers.forEach(listener => listener(message));
}
}
}

async readRoute(): Promise<string | undefined> {
return this.navigationRegistry.readRoute();
Expand Down
18 changes: 10 additions & 8 deletions packages/backend/src/utils/Publisher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,19 @@ export class Publisher<T> {
constructor(
private webview: Webview,
private channel: Messages,
private getter: () => T,
private stateGetter: () => T,
) {}

notify(): void {
this.webview
.postMessage({
protected async notify(): Promise<void> {
try {
const data = this.stateGetter();
await this.webview.postMessage({
id: this.channel,
body: this.getter(),
})
.catch((err: unknown) => {
console.error(`Something went wrong while emitting ${this.channel}: ${String(err)}`);
body: data,
});
} catch (error) {
console.error(`Error publishing to ${this.channel}:`, error);
throw error; // Re-throw to allow error handling by caller
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At the time when we created the Publisher class, we made it so the notify was not a promise, as the caller often do not want to deal with a promise.

The idea is also to consider that the notify cannot really fails, so there is no need to catch the error(s). The rare cases where it could fails would be:

  • notify is called too early in the startup of podman-desktop and the webview is not yet defined
  • notify is called during the shutdown of podman-desktop and the webview is being destroyed

IMHO those two edge case are not worth the need effort to add a try catch every-time we want to call the notify function.

}
}
79 changes: 79 additions & 0 deletions packages/backend/src/utils/StateManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**********************************************************************
* Copyright (C) 2024 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/

import { Publisher } from './Publisher';
import type { Webview } from '@podman-desktop/api';
import {
ApplicationStateError,
ApplicationStateErrorType,
type ApplicationStateErrorDetails,
} from '@shared/src/models/IError';
import type { Messages } from '@shared/Messages';

/**
* Base class for managing state with persistence and error handling
*/
export abstract class StateManager<T> extends Publisher<T> {
constructor(webview: Webview, channel: Messages, stateGetter: () => T) {
super(webview, channel, stateGetter);
}

/**
* Persists the current state and notifies subscribers
* @throws {ApplicationStateError} if persistence fails
*/
protected async persistState(): Promise<void> {
try {
await this.notify();
} catch (err: unknown) {
const details: ApplicationStateErrorDetails = {
operation: 'persist',
timestamp: Date.now(),
};
throw new ApplicationStateError(ApplicationStateErrorType.PERSISTENCE_ERROR, 'Failed to persist state', {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't have the same definition for persistence here, we usually use the persistence wording for resources saved after reboot.

Here we just send the information to the frontend (using notify), so there is nothing persisted, if the user open and leave the webview, the resources are lost, they are very volatile.

originalError: err,
details,
});
}
}

/**
* Loads persisted state
* @throws {ApplicationStateError} if loading fails
*/
protected async loadPersistedState(): Promise<void> {
try {
await this.refresh();
} catch (err: unknown) {
const details: ApplicationStateErrorDetails = {
operation: 'load',
timestamp: Date.now(),
};
throw new ApplicationStateError(ApplicationStateErrorType.LOAD_ERROR, 'Failed to load persisted state', {
originalError: err,
details,
});
}
}

/**
* Refreshes the current state
* Should be implemented by derived classes
*/
protected abstract refresh(): Promise<void>;
}
59 changes: 59 additions & 0 deletions packages/backend/src/utils/__tests__/Publisher.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { describe, expect, it, vi, beforeEach, type Mock } from 'vitest';
import { Publisher } from '../Publisher';
import type { Webview } from '@podman-desktop/api';
import { Messages } from '@shared/Messages';

interface TestState {
testData: string;
}

describe('Publisher', () => {
let mockWebview: Webview;
let publisher: Publisher<TestState>;
let mockStateGetter: Mock<() => TestState>;

beforeEach(() => {
mockWebview = {
postMessage: vi.fn().mockImplementation(() => Promise.resolve()),
} as unknown as Webview;

mockStateGetter = vi.fn().mockReturnValue({ testData: 'test' });
publisher = new Publisher<TestState>(mockWebview, Messages.MSG_ASK_ERROR_STATE, mockStateGetter);
});

it('should successfully notify with state data', async () => {
await publisher['notify']();

expect(mockStateGetter).toHaveBeenCalled();
expect(mockWebview.postMessage).toHaveBeenCalledWith({
id: Messages.MSG_ASK_ERROR_STATE,
body: { testData: 'test' },
});
});

it('should handle postMessage rejection by re-throwing', async () => {
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const error = new Error('Communication failed');
(mockWebview.postMessage as Mock).mockRejectedValueOnce(error);

await expect(publisher['notify']()).rejects.toThrow(error);

expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Error publishing to'), error);

consoleSpy.mockRestore();
});

it('should handle stateGetter errors by re-throwing', async () => {
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const error = new Error('State getter failed');
mockStateGetter.mockImplementation(() => {
throw error;
});

await expect(publisher['notify']()).rejects.toThrow(error);

expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Error publishing to'), error);

consoleSpy.mockRestore();
});
});
6 changes: 6 additions & 0 deletions packages/shared/Messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

export enum Messages {
MSG_NEW_CATALOG_STATE = 'new-catalog-state',
MSG_ASK_CATALOG_STATE = 'ask-catalog-state',
MSG_TASKS_UPDATE = 'tasks-update',
MSG_NEW_MODELS_STATE = 'new-models-state',
MSG_APPLICATIONS_STATE_UPDATE = 'applications-state-update',
Expand All @@ -32,4 +33,9 @@ export enum Messages {
MSG_PODMAN_CONNECTION_UPDATE = 'podman-connecting-update',
MSG_INSTRUCTLAB_SESSIONS_UPDATE = 'instructlab-sessions-update',
MSG_NAVIGATION_ROUTE_UPDATE = 'navigation-route-update',
MSG_NEW_ERROR_STATE = 'new-error-state',
MSG_ASK_ERROR_STATE = 'ask-error-state',
MSG_NEW_PULLED_APPLICATION_STATE = 'new-pulled-application-state',
MSG_ASK_PULLED_APPLICATIONS_STATE = 'ask-pulled-applications-state',
MSG_ACK_ERROR = 'ack-error',
}
18 changes: 18 additions & 0 deletions packages/shared/src/StudioAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ import type {
import type { ExtensionConfiguration } from './models/IExtensionConfiguration';
import type { RecipePullOptions } from './models/IRecipe';
import type { FilterRecipesResult, RecipeFilters } from './models/FilterRecipesResult';
import type { ErrorState } from './models/IError';
import type { ServiceMetadata } from './models/ServiceMetadata';

export abstract class StudioAPI {
static readonly CHANNEL: string = 'StudioAPI';
Expand Down Expand Up @@ -246,4 +248,20 @@ export abstract class StudioAPI {
* route it should use. This method has a side effect of removing the pending route after calling.
*/
abstract readRoute(): Promise<string | undefined>;

/**
* Get the current error state
*/
abstract getErrors(): Promise<ErrorState[]>;

/**
* Acknowledge an error
* @param errorId the id of the error to acknowledge
*/
abstract acknowledgeError(errorId: string): Promise<void>;

/**
* Resolve an MCP service URI (e.g. mcp://api.myservice.com) and return metadata.
*/
abstract resolveServiceUri(uri: string): Promise<ServiceMetadata>;
}
55 changes: 55 additions & 0 deletions packages/shared/src/models/IApplicationStateError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**********************************************************************
* Copyright (C) 2024 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/

export enum ApplicationStateErrorType {
PERSISTENCE_ERROR = 'PERSISTENCE_ERROR',
LOAD_ERROR = 'LOAD_ERROR',
POD_ERROR = 'POD_ERROR',
RESOURCE_ERROR = 'RESOURCE_ERROR',
GPU_ERROR = 'GPU_ERROR',
CLEANUP_ERROR = 'CLEANUP_ERROR',
MODEL_ERROR = 'MODEL_ERROR',
INFERENCE_ERROR = 'INFERENCE_ERROR',
UNKNOWN = 'UNKNOWN',
}

export class ApplicationStateError extends Error {
constructor(
public type: ApplicationStateErrorType,
message: string,
public details?: unknown,
) {
super(message);
this.name = 'ApplicationStateError';
}
}

export interface ApplicationStateErrorDetails {
recipeId?: string;
modelId?: string;
podId?: string;
operation?: string;
timestamp?: number;
resourceType?: 'memory' | 'cpu' | 'gpu' | 'disk' | 'model';
resourceDetails?: {
required?: number;
available?: number;
unit?: string;
};
cleanupStage?: 'extension' | 'playground' | 'recipe' | 'container' | 'image';
}
Loading