Skip to content
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: 1 addition & 1 deletion dashboards/src/components/Panel/Panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export const Panel = memo(function Panel(props: PanelProps) {
}

try {
const plugin = await getPlugin('Panel', panelPluginKind);
const plugin = await getPlugin({ kind: 'Panel', name: panelPluginKind });

// More defensive checking for plugin and actions
if (
Expand Down
5 changes: 4 additions & 1 deletion dashboards/src/context/DatasourceStoreProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,10 @@ export function DatasourceStoreProvider(props: DatasourceStoreProviderProps): Re
const getDatasourceClient = useCallback(
async function getClient<Client extends DatasourceClient>(selector: DatasourceSelector): Promise<Client> {
const { kind } = selector;
const [{ spec, proxyUrl }, plugin] = await Promise.all([findDatasource(selector), getPlugin('Datasource', kind)]);
const [{ spec, proxyUrl }, plugin] = await Promise.all([
findDatasource(selector),
getPlugin({ kind: 'Datasource', name: kind }),
]);

// allows extending client
const client = plugin.createClient(spec.plugin.spec, { proxyUrl }) as Client;
Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion plugin-system/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
"immer": "^10.1.1",
"react-hook-form": "^7.46.1",
"use-query-params": "^2.2.1",
"zod": "^3.25.76"
"zod": "^3.25.76",
"semver": "^7.8.0"
},
"peerDependencies": {
"@emotion/react": "^11.14.0",
Expand Down
33 changes: 15 additions & 18 deletions plugin-system/src/components/PluginRegistry/PluginRegistry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ import {
} from '../../model';
import { PluginRegistryContext } from '../../runtime';
import { useEvent } from '../../utils';
import { usePluginIndexes, getTypeAndKindKey } from './plugin-indexes';
import { usePluginIndexes, PluginCompoundKey } from './plugin-indexes';
import { resolvePluginKeys } from './getPluginSearchHelper';

export interface PluginRegistryProps {
pluginLoader: PluginLoader;
Expand Down Expand Up @@ -62,29 +63,25 @@ export function PluginRegistry(props: PluginRegistryProps): ReactElement {
});

const getPlugin = useCallback(
async <T extends PluginType>(kind: T, name: string): Promise<PluginImplementation<T>> => {
// Get the indexes of the installed plugins
async <T extends PluginType>(compoundKeyObj: PluginCompoundKey<T>): Promise<PluginImplementation<T>> => {
const pluginIndexes = await getPluginIndexes();
const { kind, name } = compoundKeyObj;

// Figure out what module the plugin is in by looking in the index
const typeAndKindKey = getTypeAndKindKey(kind, name);
const resource = pluginIndexes.pluginResourcesByNameAndKind.get(typeAndKindKey);
if (resource === undefined) {
throw new Error(`A ${name} plugin for kind '${kind}' is not installed`);
}
const candidateKeys = resolvePluginKeys(
pluginIndexes.pluginResourcesByNameKindRegistryVersion.keys(),
compoundKeyObj
);

// Treat the plugin module as a bunch of named exports that have plugins
const pluginModule = (await loadPluginModule(resource)) as Record<string, Plugin<UnknownSpec>>;
for (const resourceKey of candidateKeys) {
const resource = pluginIndexes.pluginResourcesByNameKindRegistryVersion.get(resourceKey);
if (!resource) continue;

// We currently assume that plugin modules will have named exports that match the kinds they handle
const plugin = pluginModule[name];
if (plugin === undefined) {
throw new Error(
`The ${name} plugin for kind '${kind}' is missing from the ${resource.metadata.name} plugin module`
);
const pluginModule = (await loadPluginModule(resource)) as Record<string, Plugin<UnknownSpec>>;
const plugin = pluginModule?.[resourceKey];
if (plugin) return plugin as PluginImplementation<T>;
}

return plugin as PluginImplementation<T>;
throw new Error(`A ${name} plugin for kind '${kind}' is not installed`);
},
[getPluginIndexes, loadPluginModule]
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright The Perses Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { resolvePluginKeys } from './getPluginSearchHelper';

describe('resolvePluginKeys', () => {
describe('fallback only (no version/registry in query)', () => {
it('should return the higher version when same registry', () => {
const keys = ['Panel:TimeSeriesChart:dev:1.0.0', 'Panel:TimeSeriesChart:dev:2.0.0'];
expect(resolvePluginKeys(keys, { kind: 'Panel', name: 'TimeSeriesChart' })).toEqual([
'Panel:TimeSeriesChart:dev:2.0.0',
]);
});

it('should return the higher version across registries', () => {
const keys = [
'Panel:TimeSeriesChart:dev:2.0.0',
'Panel:TimeSeriesChart::1.0.0',
'Panel:TimeSeriesChartX:dev:1.0.0',
'Panel:TimeSeriesChartX::2.0.0',
];

expect(resolvePluginKeys(keys, { kind: 'Panel', name: 'TimeSeriesChart' })).toEqual([
'Panel:TimeSeriesChart:dev:2.0.0',
]);

expect(resolvePluginKeys(keys, { kind: 'Panel', name: 'TimeSeriesChartX' })).toEqual([
'Panel:TimeSeriesChartX::2.0.0',
]);
});

it('should prefer no-registry variant on version tie by default', () => {
const keys = ['Panel:TimeSeriesChart:dev:2.0.0', 'Panel:TimeSeriesChart::2.0.0'];
expect(resolvePluginKeys(keys, { kind: 'Panel', name: 'TimeSeriesChart' })).toEqual([
'Panel:TimeSeriesChart::2.0.0',
]);
});

it('should prefer registry variant on version tie with registryOverVersion', () => {
const keys = ['Panel:TimeSeriesChart:dev:2.0.0', 'Panel:TimeSeriesChart::2.0.0'];
expect(
resolvePluginKeys(keys, { kind: 'Panel', name: 'TimeSeriesChart' }, { registryOverVersion: true })
).toEqual(['Panel:TimeSeriesChart:dev:2.0.0']);
});

it('should return empty array when no match', () => {
const keys = ['Panel:OtherChart::1.0.0'];
expect(resolvePluginKeys(keys, { kind: 'Panel', name: 'TimeSeriesChart' })).toEqual([]);
});
});

describe('exact match with version/registry', () => {
it('should return exact-match key first, then fallback', () => {
const keys = ['Panel:TimeSeriesChart:dev:1.0.0', 'Panel:TimeSeriesChart:dev:2.0.0'];
expect(
resolvePluginKeys(keys, { kind: 'Panel', name: 'TimeSeriesChart', version: '1.0.0', registry: 'dev' })
).toEqual(['Panel:TimeSeriesChart:dev:1.0.0', 'Panel:TimeSeriesChart:dev:2.0.0']);
});

it('should not duplicate if exact match is the same as fallback', () => {
const keys = ['Panel:TimeSeriesChart:dev:2.0.0'];
expect(
resolvePluginKeys(keys, { kind: 'Panel', name: 'TimeSeriesChart', version: '2.0.0', registry: 'dev' })
).toEqual(['Panel:TimeSeriesChart:dev:2.0.0']);
});

it('should include exact-match key even if it is not in allKeys', () => {
const keys = ['Panel:TimeSeriesChart:dev:2.0.0'];
expect(
resolvePluginKeys(keys, { kind: 'Panel', name: 'TimeSeriesChart', version: '3.0.0', registry: 'dev' })
).toEqual(['Panel:TimeSeriesChart:dev:3.0.0', 'Panel:TimeSeriesChart:dev:2.0.0']);
});

it('should return exact-match key with version only (no registry)', () => {
const keys = ['Panel:TimeSeriesChart::1.0.0', 'Panel:TimeSeriesChart::2.0.0'];
expect(resolvePluginKeys(keys, { kind: 'Panel', name: 'TimeSeriesChart', version: '1.0.0' })).toEqual([
'Panel:TimeSeriesChart::1.0.0',
'Panel:TimeSeriesChart::2.0.0',
]);
});
});
});
101 changes: 101 additions & 0 deletions plugin-system/src/components/PluginRegistry/getPluginSearchHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Copyright The Perses Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { gt } from 'semver';
import { PluginType, getPluginModuleCompoundKey } from '../../model';
import { PluginCompoundKey } from './plugin-indexes';

// When both a registry and non-registry variant exist at the same version,
// `registryOverVersion: true` prefers the registry variant.
export interface PluginLookupPrecedenceLogic {
registryOverVersion: boolean;
}

const PLUGIN_LOOKUP_PRECEDENCE_LOGIC: PluginLookupPrecedenceLogic = { registryOverVersion: false };

/**
* Returns an ordered list of candidate 4-part keys to try when resolving a plugin.
* If version/registry are specified, the exact-match key comes first.
* The best fallback key (highest version, tie-broken by precedence policy) follows.
*/
export const resolvePluginKeys = <T extends PluginType>(
allKeys: Iterable<string>,
query: PluginCompoundKey<T>,
precedenceLogic: PluginLookupPrecedenceLogic = PLUGIN_LOOKUP_PRECEDENCE_LOGIC
): string[] => {
const { kind, name, version, registry } = query;
const candidates: string[] = [];

// Exact match first when version or registry is specified
if (version || registry) {
candidates.push(getPluginModuleCompoundKey({ kind, name, registry, version }));
}

// Find the best fallback by scanning all matching keys
type PluginBucket = { key: string; version: string };
const latestWithRegistry: PluginBucket = { key: '', version: '' };
const latestWithoutRegistry: PluginBucket = { key: '', version: '' };

const prefix = `${kind}:${name}:`;
for (const key of allKeys) {
if (!key.startsWith(prefix)) continue;
const split = key.split(':');

if (split.length !== 4) {
console.warn(`An invalid Plugin Resource key detected during default plugin lookup: ${key}`);
continue;
}

const [, , reg, ver] = split;
if (!ver) {
console.warn(`An invalid Plugin Resource key detected during default plugin lookup: ${key}`);
continue;
}

if (reg) {
if (!latestWithRegistry.key || gt(ver, latestWithRegistry.version)) {
latestWithRegistry.key = key;
latestWithRegistry.version = ver;
}
} else {
if (!latestWithoutRegistry.key || gt(ver, latestWithoutRegistry.version)) {
latestWithoutRegistry.key = key;
latestWithoutRegistry.version = ver;
}
}
}

// Determine the best fallback key from the two buckets
let fallbackKey: string | undefined;

if (latestWithRegistry.key && latestWithoutRegistry.key) {
const { registryOverVersion } = precedenceLogic;

if (gt(latestWithRegistry.version, latestWithoutRegistry.version)) {
fallbackKey = latestWithRegistry.key;
} else if (gt(latestWithoutRegistry.version, latestWithRegistry.version)) {
fallbackKey = latestWithoutRegistry.key;
} else {
// Versions are equal — use the tie-breaker
fallbackKey = registryOverVersion ? latestWithRegistry.key : latestWithoutRegistry.key;
}
} else {
fallbackKey = latestWithRegistry.key || latestWithoutRegistry.key || undefined;
}

if (fallbackKey && !candidates.includes(fallbackKey)) {
candidates.push(fallbackKey);
}

return candidates;
};
43 changes: 25 additions & 18 deletions plugin-system/src/components/PluginRegistry/plugin-indexes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,22 @@
// limitations under the License.

import { useCallback, useRef } from 'react';
import { PluginLoader, PluginMetadataWithModule, PluginModuleResource, PluginType } from '../../model';
import {
PluginLoader,
PluginMetadataWithModule,
PluginModuleResource,
PluginType,
PluginCompoundKey,
getPluginModuleCompoundKey,
} from '../../model';
import { useEvent } from '../../utils';

export type { PluginCompoundKey };
export { getPluginModuleCompoundKey };

export interface PluginIndexes {
// Plugin resources by plugin type and kind (i.e. look up what module a plugin type and kind is in)
pluginResourcesByNameAndKind: Map<string, PluginModuleResource>;
// Plugin resources by plugin type, kind, registry, and version
pluginResourcesByNameKindRegistryVersion: Map<string, PluginModuleResource>;
// Plugin metadata by plugin type
pluginMetadataByKind: Map<PluginType, PluginMetadataWithModule[]>;
}
Expand All @@ -34,22 +44,26 @@ export function usePluginIndexes(
const installedPlugins = await getInstalledPlugins();

// Create the two indexes from the installed plugins
const pluginResourcesByNameAndKind = new Map<string, PluginModuleResource>();
const pluginResourcesByNameKindRegistryVersion = new Map<string, PluginModuleResource>();
const pluginMetadataByKind = new Map<PluginType, PluginMetadataWithModule[]>();

for (const resource of installedPlugins) {
const {
metadata: { version, registry },
} = resource;
for (const pluginMetadata of resource.spec.plugins) {
const {
kind,
spec: { name },
} = pluginMetadata;

// Index the plugin by type and kind to point at the module that contains it
const key = getTypeAndKindKey(kind, name);
if (pluginResourcesByNameAndKind.has(key)) {
console.warn(`Got more than one ${kind} plugin for kind ${name}`);
const key = getPluginModuleCompoundKey({ kind, name, registry, version });
if (pluginResourcesByNameKindRegistryVersion.has(key)) {
console.warn(
`Got more than one ${kind} plugin for kind ${name}, registry '${registry || 'undefined'}', and version '${version || 'undefined'}'`
);
}
pluginResourcesByNameAndKind.set(key, resource);
pluginResourcesByNameKindRegistryVersion.set(key, resource);

// Index the metadata by plugin type
let list = pluginMetadataByKind.get(kind);
Expand All @@ -62,7 +76,7 @@ export function usePluginIndexes(
}

return {
pluginResourcesByNameAndKind,
pluginResourcesByNameKindRegistryVersion,
pluginMetadataByKind,
};
});
Expand All @@ -76,17 +90,10 @@ export function usePluginIndexes(
pluginIndexesCache.current = request;

// Remove failed requests from the cache so they can potentially be retried
request.catch(() => pluginIndexesCache.current === undefined);
request.catch(() => (pluginIndexesCache.current = undefined));
}
return request;
}, [createPluginIndexes]);

return getPluginIndexes;
}

/**
* Gets a unique key for a plugin type/kind that can be used as a cache key.
*/
export function getTypeAndKindKey(kind: PluginType, name: string): string {
return `${kind}:${name}`;
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ export function PluginSpecEditor(props: PluginSpecEditorProps): ReactElement | n
...others
} = props;
const { data: plugin, isLoading, error } = usePlugin(pluginType, pluginKind);

if (error) {
return <ErrorAlert error={error} />;
}
Expand Down
Loading
Loading