Compare commits

..

2 Commits

Author SHA1 Message Date
Ashley Harrison e9f164d9f2 undo changes to query library cause i cba dealing with enterprise rn 2026-01-14 17:20:37 +00:00
Ashley Harrison 86fc051c58 ref changes compatible with react 18 + react 19 2026-01-14 17:08:28 +00:00
51 changed files with 62 additions and 251 deletions
-1
View File
@@ -25,7 +25,6 @@ coreroleKind: {
globalroleKind: {
kind: "GlobalRole"
pluralName: "GlobalRoles"
scope: "Cluster"
codegen: {
ts: { enabled: false }
go: { enabled: true }
+1 -1
View File
@@ -11,7 +11,7 @@ import (
// schema is unexported to prevent accidental overwrites
var (
schemaGlobalRole = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewGlobalRole(), &GlobalRoleList{}, resource.WithKind("GlobalRole"),
resource.WithPlural("globalroles"), resource.WithScope(resource.ClusterScope))
resource.WithPlural("globalroles"), resource.WithScope(resource.NamespacedScope))
kindGlobalRole = resource.Kind{
Schema: schemaGlobalRole,
Codecs: map[resource.KindEncoding]resource.Codec{
@@ -74,33 +74,6 @@ var RoleInfo = utils.NewResourceInfo(GROUP, VERSION,
},
)
var GlobalRoleInfo = globalRoleInfo.WithClusterScope()
var globalRoleInfo = utils.NewResourceInfo(GROUP, VERSION,
"globalroles", "globalrole", "GlobalRole",
func() runtime.Object { return &GlobalRole{} },
func() runtime.Object { return &GlobalRoleList{} },
utils.TableColumns{
Definition: []metav1.TableColumnDefinition{
{Name: "Name", Type: "string", Format: "name"},
{Name: "Group", Type: "string", Format: "group", Description: "Role group"},
{Name: "Title", Type: "string", Format: "string", Description: "Role name"},
{Name: "Created At", Type: "date"},
},
Reader: func(obj any) ([]interface{}, error) {
globalRole, ok := obj.(*GlobalRole)
if ok {
return []interface{}{
globalRole.Name,
globalRole.Spec.Group,
globalRole.Spec.Title,
globalRole.CreationTimestamp.UTC().Format(time.RFC3339),
}, nil
}
return nil, fmt.Errorf("expected global role")
},
},
)
var ResourcePermissionInfo = utils.NewResourceInfo(GROUP, VERSION,
"resourcepermissions", "resourcepermission", "ResourcePermission",
func() runtime.Object { return &ResourcePermission{} },
@@ -335,14 +308,6 @@ func AddResourcePermissionKnownTypes(scheme *runtime.Scheme, version schema.Grou
return nil
}
func AddGlobalRoleKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&GlobalRole{},
&GlobalRoleList{},
)
return nil
}
func AddAuthNKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
// Identity
+1 -3
View File
@@ -18,8 +18,6 @@ import (
v0alpha1 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1"
)
var ()
var appManifestData = app.ManifestData{
AppName: "iam",
Group: "iam.grafana.app",
@@ -32,7 +30,7 @@ var appManifestData = app.ManifestData{
{
Kind: "GlobalRole",
Plural: "GlobalRoles",
Scope: "Cluster",
Scope: "Namespaced",
Conversion: false,
},
-4
View File
@@ -966,10 +966,6 @@ export interface FeatureToggles {
*/
kubernetesAuthzRolesApi?: boolean;
/**
* Registers AuthZ Global Roles /apis endpoint
*/
kubernetesAuthzGlobalRolesApi?: boolean;
/**
* Registers AuthZ Role Bindings /apis endpoint
*/
kubernetesAuthzRoleBindingsApi?: boolean;
@@ -22,7 +22,7 @@ import { getBarColorByDiff, getBarColorByPackage, getBarColorByValue } from './c
import { CollapseConfig, CollapsedMap, FlameGraphDataContainer, LevelItem } from './dataTransform';
type RenderOptions = {
canvasRef: RefObject<HTMLCanvasElement>;
canvasRef: RefObject<HTMLCanvasElement | null>;
data: FlameGraphDataContainer;
root: LevelItem;
direction: 'children' | 'parents';
@@ -373,7 +373,7 @@ function useColorFunction(
);
}
function useSetupCanvas(canvasRef: RefObject<HTMLCanvasElement>, wrapperWidth: number, numberOfLevels: number) {
function useSetupCanvas(canvasRef: RefObject<HTMLCanvasElement | null>, wrapperWidth: number, numberOfLevels: number) {
const [ctx, setCtx] = useState<CanvasRenderingContext2D>();
useEffect(() => {
@@ -7,7 +7,7 @@ const CAUGHT_KEYS = ['ArrowUp', 'ArrowDown', 'Home', 'End', 'Enter', 'Tab'];
/** @internal */
export interface UseListFocusProps {
localRef: RefObject<HTMLUListElement>;
localRef: RefObject<HTMLUListElement | null>;
options: TimeOption[];
}
@@ -1,7 +1,7 @@
import { RefObject, useRef } from 'react';
export function useFocus(): [RefObject<HTMLInputElement>, () => void] {
const ref = useRef<HTMLInputElement>(null);
export function useFocus(): [RefObject<HTMLInputElement | null>, () => void] {
const ref = useRef<HTMLInputElement | null>(null);
const setFocus = () => {
ref.current && ref.current.focus();
};
@@ -6,7 +6,7 @@ const UNFOCUSED = -1;
/** @internal */
export interface UseMenuFocusProps {
localRef: RefObject<HTMLDivElement>;
localRef: RefObject<HTMLDivElement | null>;
isMenuOpen?: boolean;
close?: () => void;
onOpen?: (focusOnItem: (itemId: number) => void) => void;
@@ -22,7 +22,7 @@ interface Props extends Omit<BoxProps, 'display' | 'direction' | 'element' | 'fl
*
* https://developers.grafana.com/ui/latest/index.html?path=/docs/layout-scrollcontainer--docs
*/
export const ScrollContainer = forwardRef<HTMLDivElement, PropsWithChildren<Props>>(
export const ScrollContainer = forwardRef<HTMLDivElement | null, PropsWithChildren<Props>>(
(
{
children,
@@ -20,7 +20,7 @@ export interface TableCellTooltipProps {
field: Field;
getActions: (field: Field, rowIdx: number) => ActionModel[];
getTextColorForBackground: (bgColor: string) => string;
gridRef: RefObject<DataGridHandle>;
gridRef: RefObject<DataGridHandle | null>;
height: number;
placement?: TableCellTooltipPlacement;
renderer: TableCellRenderer;
@@ -463,7 +463,7 @@ export function useColumnResize(
return dataGridResizeHandler;
}
export function useScrollbarWidth(ref: RefObject<DataGridHandle>, height: number) {
export function useScrollbarWidth(ref: RefObject<DataGridHandle | null>, height: number) {
const [scrollbarWidth, setScrollbarWidth] = useState(0);
useLayoutEffect(() => {
@@ -135,7 +135,7 @@ export const Table = memo((props: Props) => {
// `useTableStateReducer`, which is needed to construct options for `useTable` (the hook that returns
// `toggleAllRowsExpanded`), and if we used a variable, that variable would be undefined at the time
// we initialize `useTableStateReducer`.
const toggleAllRowsExpandedRef = useRef<(value?: boolean) => void>();
const toggleAllRowsExpandedRef = useRef<((value?: boolean) => void) | null>(null);
// Internal react table state reducer
const stateReducer = useTableStateReducer({
@@ -14,8 +14,8 @@ import { GrafanaTableState } from './types';
Select the scrollbar element from the VariableSizeList scope
*/
export function useFixScrollbarContainer(
variableSizeListScrollbarRef: React.RefObject<HTMLDivElement>,
tableDivRef: React.RefObject<HTMLDivElement>
variableSizeListScrollbarRef: React.RefObject<HTMLDivElement | null>,
tableDivRef: React.RefObject<HTMLDivElement | null>
) {
useEffect(() => {
if (variableSizeListScrollbarRef.current && tableDivRef.current) {
@@ -43,7 +43,7 @@ export function useFixScrollbarContainer(
*/
export function useResetVariableListSizeCache(
extendedState: GrafanaTableState,
listRef: React.RefObject<VariableSizeList>,
listRef: React.RefObject<VariableSizeList | null>,
data: DataFrame,
hasUniqueId: boolean
) {
@@ -19,7 +19,7 @@ interface EventsCanvasProps {
}
export function EventsCanvas({ id, events, renderEventMarker, mapEventToXYCoords, config }: EventsCanvasProps) {
const plotInstance = useRef<uPlot>();
const plotInstance = useRef<uPlot | null>(null);
// render token required to re-render annotation markers. Rendering lines happens in uPlot and the props do not change
// so we need to force the re-render when the draw hook was performed by uPlot
const [renderToken, setRenderToken] = useState(0);
@@ -140,7 +140,7 @@ export const TooltipPlugin2 = ({
const [{ plot, isHovering, isPinned, contents, style, dismiss }, setState] = useReducer(mergeState, null, initState);
const sizeRef = useRef<TooltipContainerSize>();
const sizeRef = useRef<TooltipContainerSize | null>(null);
const styles = useStyles2(getStyles, maxWidth);
const renderRef = useRef(render);
@@ -96,7 +96,7 @@ export interface GraphNGState {
export class GraphNG extends Component<GraphNGProps, GraphNGState> {
static contextType = PanelContextRoot;
panelContext: PanelContext = {} as PanelContext;
private plotInstance: React.RefObject<uPlot>;
private plotInstance: React.RefObject<uPlot | null>;
private subscription = new Subscription();
-10
View File
@@ -39,9 +39,6 @@ type ApiInstaller[T runtime.Object] interface {
// while keeping the core IAM registration logic in OSS.
type RoleApiInstaller ApiInstaller[*iamv0.Role]
// GlobalRoleApiInstaller provides GlobalRole-specific API registration and validation.
type GlobalRoleApiInstaller ApiInstaller[*iamv0.GlobalRole]
// NoopApiInstaller is a no-op implementation for when roles are not available (OSS).
type NoopApiInstaller[T runtime.Object] struct {
ResourceInfo utils.ResourceInfo
@@ -80,10 +77,3 @@ func ProvideNoopRoleApiInstaller() RoleApiInstaller {
ResourceInfo: iamv0.RoleInfo,
}
}
// ProvideNoopGlobalRoleApiInstaller provides a no-op global role installer specifically for GlobalRole types.
func ProvideNoopGlobalRoleApiInstaller() GlobalRoleApiInstaller {
return &NoopApiInstaller[*iamv0.GlobalRole]{
ResourceInfo: iamv0.GlobalRoleInfo,
}
}
-3
View File
@@ -23,7 +23,6 @@ func newIAMAuthorizer(
accessClient authlib.AccessClient,
legacyAccessClient authlib.AccessClient,
roleApiInstaller RoleApiInstaller,
globalRoleApiInstaller GlobalRoleApiInstaller,
) authorizer.Authorizer {
resourceAuthorizer := make(map[string]authorizer.Authorizer)
@@ -59,8 +58,6 @@ func newIAMAuthorizer(
resourceAuthorizer["searchUsers"] = serviceAuthorizer
resourceAuthorizer["searchTeams"] = serviceAuthorizer
resourceAuthorizer[iamv0.GlobalRoleInfo.GetName()] = globalRoleApiInstaller.GetAuthorizer()
return &iamAuthorizer{resourceAuthorizer: resourceAuthorizer}
}
-1
View File
@@ -57,7 +57,6 @@ type IdentityAccessManagementAPIBuilder struct {
ssoLegacyStore *sso.LegacyStore
coreRolesStorage CoreRoleStorageBackend
roleApiInstaller RoleApiInstaller
globalRoleApiInstaller GlobalRoleApiInstaller
resourcePermissionsStorage resource.StorageBackend
roleBindingsStorage RoleBindingStorageBackend
externalGroupMappingStorage ExternalGroupMappingStorageBackend
+3 -31
View File
@@ -75,7 +75,6 @@ func RegisterAPIService(
reg prometheus.Registerer,
coreRolesStorage CoreRoleStorageBackend,
roleApiInstaller RoleApiInstaller,
globalRoleApiInstaller GlobalRoleApiInstaller,
tracing *tracing.TracingService,
roleBindingsStorage RoleBindingStorageBackend,
externalGroupMappingStorageBackend ExternalGroupMappingStorageBackend,
@@ -90,7 +89,7 @@ func RegisterAPIService(
dbProvider := legacysql.NewDatabaseProvider(sql)
store := legacy.NewLegacySQLStores(dbProvider)
legacyAccessClient := newLegacyAccessClient(ac, store)
authorizer := newIAMAuthorizer(accessClient, legacyAccessClient, roleApiInstaller, globalRoleApiInstaller)
authorizer := newIAMAuthorizer(accessClient, legacyAccessClient, roleApiInstaller)
registerMetrics(reg)
//nolint:staticcheck // not yet migrated to OpenFeature
@@ -110,7 +109,6 @@ func RegisterAPIService(
ssoLegacyStore: sso.NewLegacyStore(ssoService, tracing),
coreRolesStorage: coreRolesStorage,
roleApiInstaller: roleApiInstaller,
globalRoleApiInstaller: globalRoleApiInstaller,
resourcePermissionsStorage: resourcepermission.ProvideStorageBackend(dbProvider),
roleBindingsStorage: roleBindingsStorage,
externalGroupMappingStorage: externalGroupMappingStorageBackend,
@@ -176,7 +174,6 @@ func NewAPIService(
zTickets: make(chan bool, MaxConcurrentZanzanaWrites),
reg: reg,
roleApiInstaller: roleApiInstaller,
globalRoleApiInstaller: ProvideNoopGlobalRoleApiInstaller(), // TODO: add a proper global role installer
authorizer: authorizer.AuthorizerFunc(
func(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) {
user, ok := types.AuthInfoFrom(ctx)
@@ -222,20 +219,12 @@ func (b *IdentityAccessManagementAPIBuilder) InstallSchema(scheme *runtime.Schem
enableCoreRolesApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzCoreRolesApi, false, openfeature.TransactionContext(ctx))
enableRolesApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzRolesApi, false, openfeature.TransactionContext(ctx))
enableRoleBindingsApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzRoleBindingsApi, false, openfeature.TransactionContext(ctx))
enableGlobalRolesApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzGlobalRolesApi, false, openfeature.TransactionContext(ctx))
if enableCoreRolesApi || enableRolesApi || enableRoleBindingsApi {
if err := iamv0.AddAuthZKnownTypes(scheme); err != nil {
return err
}
}
if enableGlobalRolesApi {
if err := iamv0.AddGlobalRoleKnownTypes(scheme); err != nil {
return err
}
}
//nolint:staticcheck // not yet migrated to OpenFeature
if b.features.IsEnabledGlobally(featuremgmt.FlagKubernetesAuthzResourcePermissionApis) {
if err := iamv0.AddResourcePermissionKnownTypes(scheme, iamv0.SchemeGroupVersion); err != nil {
@@ -275,7 +264,6 @@ func (b *IdentityAccessManagementAPIBuilder) UpdateAPIGroupInfo(apiGroupInfo *ge
enableCoreRolesApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzCoreRolesApi, false, openfeature.TransactionContext(ctx))
enableRolesApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzRolesApi, false, openfeature.TransactionContext(ctx))
enableRoleBindingsApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzRoleBindingsApi, false, openfeature.TransactionContext(ctx))
enableGlobalRolesApi := client.Boolean(ctx, featuremgmt.FlagKubernetesAuthzGlobalRolesApi, false, openfeature.TransactionContext(ctx))
// teams + users must have shorter names because they are often used as part of another name
opts.StorageOptsRegister(iamv0.TeamResourceInfo.GroupResource(), apistore.StorageOptions{
@@ -325,12 +313,6 @@ func (b *IdentityAccessManagementAPIBuilder) UpdateAPIGroupInfo(apiGroupInfo *ge
}
}
if enableGlobalRolesApi {
if err := b.globalRoleApiInstaller.RegisterStorage(apiGroupInfo, &opts, storage); err != nil {
return err
}
}
if enableRoleBindingsApi {
if err := b.UpdateRoleBindingsAPIGroup(apiGroupInfo, opts, storage, enableZanzanaSync); err != nil {
return err
@@ -682,8 +664,6 @@ func (b *IdentityAccessManagementAPIBuilder) Validate(ctx context.Context, a adm
return externalgroupmapping.ValidateOnCreate(typedObj)
case *iamv0.Role:
return b.roleApiInstaller.ValidateOnCreate(ctx, typedObj)
case *iamv0.GlobalRole:
return b.globalRoleApiInstaller.ValidateOnCreate(ctx, typedObj)
}
return nil
case admission.Update:
@@ -714,20 +694,12 @@ func (b *IdentityAccessManagementAPIBuilder) Validate(ctx context.Context, a adm
return fmt.Errorf("expected old object to be a Role, got %T", oldRoleObj)
}
return b.roleApiInstaller.ValidateOnUpdate(ctx, oldRoleObj, typedObj)
case *iamv0.GlobalRole:
oldGlobalRoleObj, ok := a.GetOldObject().(*iamv0.GlobalRole)
if !ok {
return fmt.Errorf("expected old object to be a GlobalRole, got %T", oldGlobalRoleObj)
}
return b.globalRoleApiInstaller.ValidateOnUpdate(ctx, oldGlobalRoleObj, typedObj)
}
return nil
case admission.Delete:
switch oldObj := a.GetOldObject().(type) {
switch oldRoleObj := a.GetOldObject().(type) {
case *iamv0.Role:
return b.roleApiInstaller.ValidateOnDelete(ctx, oldObj)
case *iamv0.GlobalRole:
return b.globalRoleApiInstaller.ValidateOnDelete(ctx, oldObj)
return b.roleApiInstaller.ValidateOnDelete(ctx, oldRoleObj)
}
return nil
case admission.Connect:
-1
View File
@@ -29,7 +29,6 @@ var WireSetExts = wire.NewSet(
noopstorage.ProvideStorageBackend,
wire.Bind(new(iam.CoreRoleStorageBackend), new(*noopstorage.StorageBackendImpl)),
iam.ProvideNoopRoleApiInstaller,
iam.ProvideNoopGlobalRoleApiInstaller,
wire.Bind(new(iam.RoleBindingStorageBackend), new(*noopstorage.StorageBackendImpl)),
wire.Bind(new(iam.ExternalGroupMappingStorageBackend), new(*noopstorage.StorageBackendImpl)),
+2 -4
View File
@@ -882,9 +882,8 @@ func Initialize(ctx context.Context, cfg *setting.Cfg, opts Options, apiOpts api
folderAPIBuilder := folders.RegisterAPIService(cfg, featureToggles, apiserverService, folderimplService, folderPermissionsService, accessControl, acimplService, accessClient, registerer, resourceClient, zanzanaClient)
storageBackendImpl := noopstorage.ProvideStorageBackend()
roleApiInstaller := iam.ProvideNoopRoleApiInstaller()
globalRoleApiInstaller := iam.ProvideNoopGlobalRoleApiInstaller()
noopTeamGroupsREST := externalgroupmapping.ProvideNoopTeamGroupsREST()
identityAccessManagementAPIBuilder, err := iam.RegisterAPIService(cfg, featureToggles, apiserverService, ssosettingsimplService, sqlStore, accessControl, accessClient, zanzanaClient, registerer, storageBackendImpl, roleApiInstaller, globalRoleApiInstaller, tracingService, storageBackendImpl, storageBackendImpl, noopTeamGroupsREST, dualwriteService, resourceClient, orgService, userService, teamService, eventualRestConfigProvider)
identityAccessManagementAPIBuilder, err := iam.RegisterAPIService(cfg, featureToggles, apiserverService, ssosettingsimplService, sqlStore, accessControl, accessClient, zanzanaClient, registerer, storageBackendImpl, roleApiInstaller, tracingService, storageBackendImpl, storageBackendImpl, noopTeamGroupsREST, dualwriteService, resourceClient, orgService, userService, teamService, eventualRestConfigProvider)
if err != nil {
return nil, err
}
@@ -1551,9 +1550,8 @@ func InitializeForTest(ctx context.Context, t sqlutil.ITestDB, testingT interfac
folderAPIBuilder := folders.RegisterAPIService(cfg, featureToggles, apiserverService, folderimplService, folderPermissionsService, accessControl, acimplService, accessClient, registerer, resourceClient, zanzanaClient)
storageBackendImpl := noopstorage.ProvideStorageBackend()
roleApiInstaller := iam.ProvideNoopRoleApiInstaller()
globalRoleApiInstaller := iam.ProvideNoopGlobalRoleApiInstaller()
noopTeamGroupsREST := externalgroupmapping.ProvideNoopTeamGroupsREST()
identityAccessManagementAPIBuilder, err := iam.RegisterAPIService(cfg, featureToggles, apiserverService, ssosettingsimplService, sqlStore, accessControl, accessClient, zanzanaClient, registerer, storageBackendImpl, roleApiInstaller, globalRoleApiInstaller, tracingService, storageBackendImpl, storageBackendImpl, noopTeamGroupsREST, dualwriteService, resourceClient, orgService, userService, teamService, eventualRestConfigProvider)
identityAccessManagementAPIBuilder, err := iam.RegisterAPIService(cfg, featureToggles, apiserverService, ssosettingsimplService, sqlStore, accessControl, accessClient, zanzanaClient, registerer, storageBackendImpl, roleApiInstaller, tracingService, storageBackendImpl, storageBackendImpl, noopTeamGroupsREST, dualwriteService, resourceClient, orgService, userService, teamService, eventualRestConfigProvider)
if err != nil {
return nil, err
}
-7
View File
@@ -1597,13 +1597,6 @@ var (
Owner: identityAccessTeam,
HideFromDocs: true,
},
{
Name: "kubernetesAuthzGlobalRolesApi",
Description: "Registers AuthZ Global Roles /apis endpoint",
Stage: FeatureStageExperimental,
Owner: identityAccessTeam,
HideFromDocs: true,
},
{
Name: "kubernetesAuthzRoleBindingsApi",
Description: "Registers AuthZ Role Bindings /apis endpoint",
-1
View File
@@ -219,7 +219,6 @@ kubernetesAuthzResourcePermissionApis,experimental,@grafana/identity-access-team
kubernetesAuthzZanzanaSync,experimental,@grafana/identity-access-team,false,false,false
kubernetesAuthzCoreRolesApi,experimental,@grafana/identity-access-team,false,false,false
kubernetesAuthzRolesApi,experimental,@grafana/identity-access-team,false,false,false
kubernetesAuthzGlobalRolesApi,experimental,@grafana/identity-access-team,false,false,false
kubernetesAuthzRoleBindingsApi,experimental,@grafana/identity-access-team,false,false,false
kubernetesAuthnMutation,experimental,@grafana/identity-access-team,false,false,false
kubernetesExternalGroupMapping,experimental,@grafana/identity-access-team,false,false,false
1 Name Stage Owner requiresDevMode RequiresRestart FrontendOnly
219 kubernetesAuthzZanzanaSync experimental @grafana/identity-access-team false false false
220 kubernetesAuthzCoreRolesApi experimental @grafana/identity-access-team false false false
221 kubernetesAuthzRolesApi experimental @grafana/identity-access-team false false false
kubernetesAuthzGlobalRolesApi experimental @grafana/identity-access-team false false false
222 kubernetesAuthzRoleBindingsApi experimental @grafana/identity-access-team false false false
223 kubernetesAuthnMutation experimental @grafana/identity-access-team false false false
224 kubernetesExternalGroupMapping experimental @grafana/identity-access-team false false false
-4
View File
@@ -650,10 +650,6 @@ const (
// Registers AuthZ Roles /apis endpoint
FlagKubernetesAuthzRolesApi = "kubernetesAuthzRolesApi"
// FlagKubernetesAuthzGlobalRolesApi
// Registers AuthZ Global Roles /apis endpoint
FlagKubernetesAuthzGlobalRolesApi = "kubernetesAuthzGlobalRolesApi"
// FlagKubernetesAuthzRoleBindingsApi
// Registers AuthZ Role Bindings /apis endpoint
FlagKubernetesAuthzRoleBindingsApi = "kubernetesAuthzRoleBindingsApi"
-13
View File
@@ -2024,19 +2024,6 @@
"hideFromDocs": true
}
},
{
"metadata": {
"name": "kubernetesAuthzGlobalRolesApi",
"resourceVersion": "1768294340511",
"creationTimestamp": "2026-01-13T08:52:20Z"
},
"spec": {
"description": "Registers AuthZ Global Roles /apis endpoint",
"stage": "experimental",
"codeowner": "@grafana/identity-access-team",
"hideFromDocs": true
}
},
{
"metadata": {
"name": "kubernetesAuthzResourcePermissionApis",
@@ -109,7 +109,7 @@ const defaultMatchers = {
* "Time as X" core component, expects ascending x
*/
export class GraphNG extends Component<GraphNGProps, GraphNGState> {
private plotInstance: React.RefObject<uPlot>;
private plotInstance: React.RefObject<uPlot | null>;
constructor(props: GraphNGProps) {
super(props);
@@ -33,7 +33,7 @@ global.ResizeObserver = jest.fn().mockImplementation((callback) => {
});
// Helper function to assign a mock div to a ref
function assignMockDivToRef(ref: React.RefObject<HTMLDivElement>, mockDiv: HTMLDivElement) {
function assignMockDivToRef(ref: React.RefObject<HTMLDivElement | null>, mockDiv: HTMLDivElement) {
// Use type assertion to bypass readonly restriction in tests
(ref as { current: HTMLDivElement | null }).current = mockDiv;
}
@@ -8,7 +8,7 @@ import grafanaTextLogoDarkSvg from 'img/grafana_text_logo_dark.svg';
import grafanaTextLogoLightSvg from 'img/grafana_text_logo_light.svg';
interface SoloPanelPageLogoProps {
containerRef: React.RefObject<HTMLDivElement>;
containerRef: React.RefObject<HTMLDivElement | null>;
isHovered: boolean;
hideLogo?: UrlQueryValue;
}
@@ -61,7 +61,7 @@ interface State {
class UnThemedTransformationsEditor extends React.PureComponent<TransformationsEditorProps, State> {
subscription?: Unsubscribable;
ref: RefObject<HTMLDivElement>;
ref: RefObject<HTMLDivElement | null>;
constructor(props: TransformationsEditorProps) {
super(props);
@@ -43,7 +43,7 @@ export const LibraryPanelsView = ({
}
);
const asyncDispatch = useMemo(() => asyncDispatcher(dispatch), [dispatch]);
const abortControllerRef = useRef<AbortController>();
const abortControllerRef = useRef<AbortController | null>(null);
useDebounce(
() => {
@@ -12,7 +12,7 @@ export interface Props {}
export const LiveConnectionWarning = memo(function LiveConnectionWarning() {
const [show, setShow] = useState<boolean | undefined>(undefined);
const subscriptionRef = useRef<Unsubscribable>();
const subscriptionRef = useRef<Unsubscribable | null>(null);
const styles = useStyles2(getStyle);
useEffect(() => {
@@ -2,9 +2,8 @@ import { render, screen } from '@testing-library/react';
import { defaultsDeep } from 'lodash';
import { Provider } from 'react-redux';
import { CoreApp, EventBusSrv, FieldType, getDefaultTimeRange, LoadingState } from '@grafana/data';
import { config, PanelDataErrorViewProps } from '@grafana/runtime';
import { usePanelContext } from '@grafana/ui';
import { FieldType, getDefaultTimeRange, LoadingState } from '@grafana/data';
import { PanelDataErrorViewProps } from '@grafana/runtime';
import { configureStore } from 'app/store/configureStore';
import { PanelDataErrorView } from './PanelDataErrorView';
@@ -17,24 +16,7 @@ jest.mock('app/features/dashboard/services/DashboardSrv', () => ({
},
}));
jest.mock('@grafana/ui', () => ({
...jest.requireActual('@grafana/ui'),
usePanelContext: jest.fn(),
}));
const mockUsePanelContext = jest.mocked(usePanelContext);
const RUN_QUERY_MESSAGE = 'Run a query to visualize it here or go to all visualizations to add other panel types';
const panelContextRoot = {
app: CoreApp.Dashboard,
eventsScope: 'global',
eventBus: new EventBusSrv(),
};
describe('PanelDataErrorView', () => {
beforeEach(() => {
mockUsePanelContext.mockReturnValue(panelContextRoot);
});
it('show No data when there is no data', () => {
renderWithProps();
@@ -88,45 +70,6 @@ describe('PanelDataErrorView', () => {
expect(screen.getByText('Query returned nothing')).toBeInTheDocument();
});
it('should show "Run a query..." message when no query is configured and feature toggle is enabled', () => {
mockUsePanelContext.mockReturnValue(panelContextRoot);
const originalFeatureToggle = config.featureToggles.newVizSuggestions;
config.featureToggles.newVizSuggestions = true;
renderWithProps({
data: {
state: LoadingState.Done,
series: [],
timeRange: getDefaultTimeRange(),
},
});
expect(screen.getByText(RUN_QUERY_MESSAGE)).toBeInTheDocument();
config.featureToggles.newVizSuggestions = originalFeatureToggle;
});
it('should show "No data" message when feature toggle is disabled even without queries', () => {
mockUsePanelContext.mockReturnValue(panelContextRoot);
const originalFeatureToggle = config.featureToggles.newVizSuggestions;
config.featureToggles.newVizSuggestions = false;
renderWithProps({
data: {
state: LoadingState.Done,
series: [],
timeRange: getDefaultTimeRange(),
},
});
expect(screen.getByText('No data')).toBeInTheDocument();
expect(screen.queryByText(RUN_QUERY_MESSAGE)).not.toBeInTheDocument();
config.featureToggles.newVizSuggestions = originalFeatureToggle;
});
});
function renderWithProps(overrides?: Partial<PanelDataErrorViewProps>) {
@@ -5,15 +5,14 @@ import {
FieldType,
getPanelDataSummary,
GrafanaTheme2,
PanelData,
PanelDataSummary,
PanelPluginVisualizationSuggestion,
} from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';
import { t, Trans } from '@grafana/i18n';
import { PanelDataErrorViewProps, locationService, config } from '@grafana/runtime';
import { PanelDataErrorViewProps, locationService } from '@grafana/runtime';
import { VizPanel } from '@grafana/scenes';
import { Icon, usePanelContext, useStyles2 } from '@grafana/ui';
import { usePanelContext, useStyles2 } from '@grafana/ui';
import { CardButton } from 'app/core/components/CardButton';
import { LS_VISUALIZATION_SELECT_TAB_KEY } from 'app/core/constants';
import store from 'app/core/store';
@@ -25,11 +24,6 @@ import { findVizPanelByKey, getVizPanelKeyForPanelId } from 'app/features/dashbo
import { useDispatch } from 'app/types/store';
import { changePanelPlugin } from '../state/actions';
import { hasData } from '../suggestions/utils';
function hasNoQueryConfigured(data: PanelData): boolean {
return !data.request?.targets || data.request.targets.length === 0;
}
export function PanelDataErrorView(props: PanelDataErrorViewProps) {
const styles = useStyles2(getStyles);
@@ -99,14 +93,8 @@ export function PanelDataErrorView(props: PanelDataErrorViewProps) {
}
};
const noData = !hasData(props.data);
const noQueryConfigured = hasNoQueryConfigured(props.data);
const showEmptyState =
config.featureToggles.newVizSuggestions && context.app === CoreApp.PanelEditor && noQueryConfigured && noData;
return (
<div className={styles.wrapper}>
{showEmptyState && <Icon name="chart-line" size="xxxl" className={styles.emptyStateIcon} />}
<div className={styles.message} data-testid={selectors.components.Panels.Panel.PanelDataErrorMessage}>
{message}
</div>
@@ -143,17 +131,7 @@ function getMessageFor(
return message;
}
const noData = !hasData(data);
const noQueryConfigured = hasNoQueryConfigured(data);
if (config.featureToggles.newVizSuggestions && noQueryConfigured && noData) {
return t(
'dashboard.new-panel.empty-state-message',
'Run a query to visualize it here or go to all visualizations to add other panel types'
);
}
if (noData) {
if (!data.series || data.series.length === 0 || data.series.every((frame) => frame.length === 0)) {
return fieldConfig?.defaults.noValue ?? t('panel.panel-data-error-view.no-value.default', 'No data');
}
@@ -198,9 +176,5 @@ const getStyles = (theme: GrafanaTheme2) => {
width: '100%',
maxWidth: '600px',
}),
emptyStateIcon: css({
color: theme.colors.text.secondary,
marginBottom: theme.spacing(2),
}),
};
};
@@ -38,7 +38,7 @@ export function useSearchKeyboardNavigation(
): ItemSelection {
const highlightIndexRef = useRef<ItemSelection>({ x: 0, y: -1 });
const [highlightIndex, setHighlightIndex] = useState<ItemSelection>({ x: 0, y: -1 });
const urlsRef = useRef<Field>();
const urlsRef = useRef<Field | null>(null);
// Clear selection when the search results change
useEffect(() => {
@@ -77,7 +77,7 @@ export const SuggestionsInput = ({
const theme = useTheme2();
const styles = getStyles(theme, inputHeight);
const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement>();
const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement | null>(null);
useEffect(() => {
scrollRef.current?.scrollTo(0, scrollTop);
@@ -11,7 +11,7 @@ import checkboxWhitePng from 'img/checkbox_white.png';
import { ALL_VARIABLE_VALUE } from '../../constants';
export interface Props extends React.HTMLProps<HTMLUListElement>, Themeable2 {
export interface Props extends Omit<React.HTMLProps<HTMLUListElement>, 'onToggle'>, Themeable2 {
multi: boolean;
values: VariableOption[];
selectedValues: VariableOption[];
@@ -20,8 +20,8 @@ interface CodeEditorProps {
export const LogsQLCodeEditor = (props: CodeEditorProps) => {
const { query, datasource, onChange } = props;
const monacoRef = useRef<Monaco>();
const disposalRef = useRef<monacoType.IDisposable>();
const monacoRef = useRef<Monaco | null>(null);
const disposalRef = useRef<monacoType.IDisposable | undefined>(undefined);
const onFocus = useCallback(async () => {
disposalRef.current = await reRegisterCompletionProvider(
@@ -42,8 +42,8 @@ interface LogsCodeEditorProps {
export const PPLQueryEditor = (props: LogsCodeEditorProps) => {
const { query, datasource, onChange } = props;
const monacoRef = useRef<Monaco>();
const disposalRef = useRef<monacoType.IDisposable>();
const monacoRef = useRef<Monaco | null>(null);
const disposalRef = useRef<monacoType.IDisposable | undefined>(undefined);
const onFocus = useCallback(async () => {
disposalRef.current = await reRegisterCompletionProvider(
@@ -20,8 +20,8 @@ interface SQLCodeEditorProps {
export const SQLQueryEditor = (props: SQLCodeEditorProps) => {
const { query, datasource, onChange } = props;
const monacoRef = useRef<Monaco>();
const disposalRef = useRef<monacoType.IDisposable>();
const monacoRef = useRef<Monaco | null>(null);
const disposalRef = useRef<monacoType.IDisposable | undefined>(undefined);
const onFocus = useCallback(async () => {
disposalRef.current = await reRegisterCompletionProvider(
@@ -94,7 +94,7 @@ const EDITOR_HEIGHT_OFFSET = 2;
* Hook that returns function that will set up monaco autocomplete for the label selector
*/
function useAutocomplete(getLabelValues: (label: string) => Promise<string[]>, labels?: string[]) {
const providerRef = useRef<CompletionProvider>();
const providerRef = useRef<CompletionProvider | null>(null);
if (providerRef.current === undefined) {
providerRef.current = new CompletionProvider();
}
@@ -126,7 +126,7 @@ export function LokiContextUi(props: LokiContextUiProps) {
window.localStorage.getItem(SHOULD_INCLUDE_PIPELINE_OPERATIONS) === 'true'
);
const timerHandle = useRef<number>();
const timerHandle = useRef<number | null>(null);
const previousInitialized = useRef<boolean>(false);
const previousContextFilters = useRef<ContextFilter[]>([]);
@@ -191,14 +191,18 @@ export function LokiContextUi(props: LokiContextUiProps) {
}, 1500);
return () => {
clearTimeout(timerHandle.current);
if (timerHandle.current) {
clearTimeout(timerHandle.current);
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [contextFilters, initialized]);
useEffect(() => {
return () => {
clearTimeout(timerHandle.current);
if (timerHandle.current) {
clearTimeout(timerHandle.current);
}
onClose();
};
}, [onClose]);
@@ -52,7 +52,7 @@ export function TraceQLEditor(props: Props) {
const onRunQueryRef = useRef(onRunQuery);
onRunQueryRef.current = onRunQuery;
const errorTimeoutId = useRef<number>();
const errorTimeoutId = useRef<number | null>(null);
return (
<>
@@ -103,7 +103,9 @@ export function TraceQLEditor(props: Props) {
}
// Remove previous callback if existing, to prevent squiggles from been shown while the user is still typing
window.clearTimeout(errorTimeoutId.current);
if (errorTimeoutId.current) {
window.clearTimeout(errorTimeoutId.current);
}
const errorNodes = getErrorNodes(model.getValue());
const cursorPosition = changeEvent.changes[0].rangeOffset;
@@ -1,5 +1,5 @@
export function renderHistogram(
can: React.RefObject<HTMLCanvasElement>,
can: React.RefObject<HTMLCanvasElement | null>,
histCanWidth: number,
histCanHeight: number,
xVals: number[],
+1 -1
View File
@@ -196,7 +196,7 @@ export const LogsPanel = ({
const dataSourcesMap = useDatasourcesFromTargets(panelData.request?.targets);
// Prevents the scroll position to change when new data from infinite scrolling is received
const keepScrollPositionRef = useRef<null | 'infinite-scroll' | 'user'>(null);
let closeCallback = useRef<() => void>();
const closeCallback = useRef<(() => void) | null>(null);
const { app, eventBus, onAddAdHocFilter } = usePanelContext();
useEffect(() => {
+1 -1
View File
@@ -70,7 +70,7 @@ export function useLayout(
const currentSignature = createDataSignature(rawNodes, rawEdges);
const isMounted = useMountedState();
const layoutWorkerCancelRef = useRef<(() => void) | undefined>();
const layoutWorkerCancelRef = useRef<(() => void) | null>(null);
useUnmount(() => {
if (layoutWorkerCancelRef.current) {
@@ -133,7 +133,7 @@ export const AnnotationsPlugin2 = ({
const newRangeRef = useRef(newRange);
newRangeRef.current = newRange;
const xAxisRef = useRef<HTMLDivElement>();
const xAxisRef = useRef<HTMLDivElement | null>(null);
useLayoutEffect(() => {
config.addHook('ready', (u) => {
@@ -23,7 +23,7 @@ export const ExemplarsPlugin = ({
maxHeight,
maxWidth,
}: ExemplarsPluginProps) => {
const plotInstance = useRef<uPlot>();
const plotInstance = useRef<uPlot | null>(null);
const [lockedExemplarRowIndex, setLockedExemplarRowIndex] = useState<number | undefined>();
@@ -11,7 +11,7 @@ interface ThresholdControlsPluginProps {
}
export const OutsideRangePlugin = ({ config, onChangeTimeRange }: ThresholdControlsPluginProps) => {
const plotInstance = useRef<uPlot>();
const plotInstance = useRef<uPlot | null>(null);
const [timevalues, setTimeValues] = useState<number[] | TypedArray>([]);
const [timeRange, setTimeRange] = useState<Scale | undefined>();
@@ -16,7 +16,7 @@ interface ThresholdControlsPluginProps {
}
export const ThresholdControlsPlugin = ({ config, fieldConfig, onThresholdsChange }: ThresholdControlsPluginProps) => {
const plotInstance = useRef<uPlot>();
const plotInstance = useRef<uPlot | null>(null);
const [renderToken, setRenderToken] = useState(0);
useLayoutEffect(() => {