import { useMemo } from 'react'; import { LINKING_STATUS_ANNOTATION } from '~/consts/secrets'; import { useK8sWatchResource } from '~/k8s'; import { ServiceAccountGroupVersionKind, ServiceAccountModel } from '~/models'; import { SecretKind, ServiceAccountKind } from '~/types'; import { filterLinkedServiceAccounts } from '~/utils/service-account/service-account-utils'; import { BackgroundJobStatus } from '~/utils/task-store'; export const useLinkedServiceAccounts = (namespace: string, secert: SecretKind, watch: boolean) => { const { data: serviceAccounts, isLoading, error, } = useK8sWatchResource( { groupVersionKind: ServiceAccountGroupVersionKind, // the name field is used to refresh status when annotations is updating. name: secert.metadata?.annotations?.[LINKING_STATUS_ANNOTATION], namespace, isList: true, watch, }, ServiceAccountModel, ); const linkedServiceAccounts: ServiceAccountKind[] = useMemo(() => { if (isLoading || !serviceAccounts) return []; const taskStatus = secert.metadata?.annotations?.[LINKING_STATUS_ANNOTATION]; const isFinished = [BackgroundJobStatus.Succeeded, BackgroundJobStatus.Failed].includes( taskStatus as BackgroundJobStatus, ); if (!isFinished) { return []; } return filterLinkedServiceAccounts(secert.metadata?.name, serviceAccounts); }, [secert, serviceAccounts, isLoading]); return { linkedServiceAccounts, isLoading, error, }; };