You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@apisix.apache.org by "Baluduvamsi2006 (via GitHub)" <gi...@apache.org> on 2026/02/19 23:27:27 UTC
[PR] refactor(ui): introduce ResourceListPage and standardize resource lis… [apisix-dashboard]
Baluduvamsi2006 opened a new pull request, #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305
### What this PR does
This PR introduces a reusable `ResourceListPage` component and refactors existing resource list pages to use it.
Previously, each resource list page (Services, Routes, Consumers, Upstreams, etc.) duplicated the same ProTable setup, pagination handling, toolbar logic, page header, and empty-state behavior. This duplication made maintenance harder and increased the risk of inconsistencies.
With this change:
- Common list-page logic is centralized in `ResourceListPage`
- Resource pages now only define resource-specific columns and hooks
- UI behavior, DOM structure, and user experience remain unchanged
- Future list-page updates can be applied in a single place
Additionally, this PR improves E2E test stability by tightening selectors, improving cross-platform path handling, and reducing flakiness during parallel execution.
### Why this change is needed
- Reduces duplicated boilerplate across multiple pages
- Improves long-term maintainability
- Keeps list-page behavior consistent across the dashboard
- Improves test reliability without changing functionality
### Checklist
- [x] UI refactor only (no API or behavior changes)
- [x] Backward compatible
- [x] Lint passed
- [x] Build passed
- [x] E2E tests passing
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource lis… [apisix-dashboard]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#discussion_r2844900204
##########
src/components/page/ResourceListPage.tsx:
##########
@@ -0,0 +1,112 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 type { ProColumns } from '@ant-design/pro-components';
+import { ProTable } from '@ant-design/pro-components';
+import type { TablePaginationConfig } from 'antd';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { APISIXListResponse } from '@/types/schema/apisix/type';
+
+import PageHeader from './PageHeader';
+import { ToAddPageBtn } from './ToAddPageBtn';
+
+interface ResourceListPageProps<T> {
+ titleKey?: string;
+ columns: ProColumns<T>[];
+ queryHook: () => {
+ data?: APISIXListResponse<T> | undefined;
+ isLoading: boolean;
+ pagination: TablePaginationConfig | false;
+ refetch?: () => void;
+ };
+ rowKey: string;
+ addPageTo?: string;
+ resourceNameKey?: string;
+ emptyKey?: string;
+}
+
+const ResourceListPage = <T extends Record<string, unknown>>(
+ props: ResourceListPageProps<T>
+) => {
+ const {
+ titleKey,
+ columns,
+ queryHook,
+ rowKey,
+ addPageTo,
+ resourceNameKey,
+ emptyKey,
+ } = props;
+ const { t } = useTranslation();
+ const { data, isLoading, pagination } = queryHook();
+
+ const dataSource = useMemo(() => (data?.list as T[]) ?? [], [data]);
+ const total = pagination?.total ?? data?.total ?? 0;
+
+ const paginationConfig = useMemo(() => {
+ if (pagination === false) return false;
+
+ return {
+ current: pagination?.current ?? 1,
+ pageSize: pagination?.pageSize ?? 10,
+ total,
+ showSizeChanger: true,
+ pageSizeOptions: [10, 20, 50, 100],
+ hideOnSinglePage: false,
+ onChange: pagination?.onChange,
+ showTotal: (total: number, range: [number, number]) =>
+ `${range[0]}-${range[1]} of ${total} items`,
+ };
+ }, [pagination, total]);
+
+ return (
+ <>
+ {titleKey && <PageHeader title={t(titleKey as never)} />}
+ <ProTable<T>
+ columns={columns}
+ dataSource={dataSource}
+ rowKey={rowKey}
+ loading={isLoading}
+ search={false}
+ options={{ reload: true, density: true, setting: true }}
Review Comment:
The `options` prop is set to an object with reload, density, and setting features enabled, but the original implementations used `options={false}` to disable table options. This changes the user interface by adding table toolbar options that were not present before, deviating from the claimed "UI behavior, DOM structure, and user experience remain unchanged" in the PR description.
```suggestion
options={false}
```
##########
src/components/page/ResourceListPage.tsx:
##########
@@ -0,0 +1,112 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 type { ProColumns } from '@ant-design/pro-components';
+import { ProTable } from '@ant-design/pro-components';
+import type { TablePaginationConfig } from 'antd';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { APISIXListResponse } from '@/types/schema/apisix/type';
+
+import PageHeader from './PageHeader';
+import { ToAddPageBtn } from './ToAddPageBtn';
+
+interface ResourceListPageProps<T> {
+ titleKey?: string;
+ columns: ProColumns<T>[];
+ queryHook: () => {
+ data?: APISIXListResponse<T> | undefined;
+ isLoading: boolean;
+ pagination: TablePaginationConfig | false;
+ refetch?: () => void;
+ };
+ rowKey: string;
+ addPageTo?: string;
+ resourceNameKey?: string;
+ emptyKey?: string;
+}
+
+const ResourceListPage = <T extends Record<string, unknown>>(
+ props: ResourceListPageProps<T>
+) => {
+ const {
+ titleKey,
+ columns,
+ queryHook,
+ rowKey,
+ addPageTo,
+ resourceNameKey,
+ emptyKey,
+ } = props;
+ const { t } = useTranslation();
+ const { data, isLoading, pagination } = queryHook();
Review Comment:
The `queryHook` is called directly in the component body (line 56) without being wrapped in a useMemo or useCallback. This means a new query hook instance is created on every render because the arrow function `() => ({ data, isLoading, pagination, refetch })` passed to queryHook in the route components creates a new reference each time. This will cause the query to be re-executed unnecessarily on every render, potentially leading to performance issues and infinite re-render loops.
##########
src/routes/upstreams/index.tsx:
##########
@@ -15,24 +15,22 @@
* limitations under the License.
*/
import type { ProColumns } from '@ant-design/pro-components';
-import { ProTable } from '@ant-design/pro-components';
import { createFileRoute } from '@tanstack/react-router';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { getUpstreamListQueryOptions, useUpstreamList } from '@/apis/hooks';
import { DeleteResourceBtn } from '@/components/page/DeleteResourceBtn';
-import PageHeader from '@/components/page/PageHeader';
-import { ToAddPageBtn, ToDetailPageBtn } from '@/components/page/ToAddPageBtn';
-import { AntdConfigProvider } from '@/config/antdConfigProvider';
+import ResourceListPage from '@/components/page/ResourceListPage';
+import { ToDetailPageBtn } from '@/components/page/ToAddPageBtn';
import { API_UPSTREAMS } from '@/config/constant';
import { queryClient } from '@/config/global';
import type { APISIXType } from '@/types/schema/apisix';
import { pageSearchSchema } from '@/types/schema/pageSearch';
-function RouteComponent() {
+const RouteComponent = () => {
const { t } = useTranslation();
- const { data, isLoading, refetch, pagination } = useUpstreamList();
+ const { data, isLoading, pagination, refetch } = useUpstreamList();
Review Comment:
The `refetch` value from the query hook is destructured but never used or passed to ResourceListPage. The original implementations passed `refetch` to action buttons in columns (e.g., DeleteResourceBtn). While the columns still receive refetch through closure, this inconsistency suggests the refetch mechanism might not work properly with the new component pattern, as there's no way to trigger refetch from the ResourceListPage component itself (e.g., through a refresh button).
##########
src/apis/hooks.ts:
##########
@@ -85,9 +90,10 @@ export const genUseList = <
return (replaceKey?: U, defaultParams?: Partial<P>) => {
const key = replaceKey || routeKey;
const { params, setParams } = useSearchParams<T | U, P>(key);
- const listQuery = useSuspenseQuery(
- listQueryOptions({ ...defaultParams, ...params })
- );
+ const listQuery = useQuery({
Review Comment:
Changing from `useSuspenseQuery` to `useQuery` removes React Suspense support. This is a breaking change that affects how the application handles loading states and could cause issues with error boundaries and loading UI. The route loaders are being removed (as seen in services/index.tsx and routes/index.tsx), which means data is no longer being prefetched before navigation. This fundamentally changes the data loading behavior from suspense-based prefetching to on-demand loading, which contradicts the PR description claim that "UI behavior, DOM structure, and user experience remain unchanged".
```suggestion
const listQuery = useSuspenseQuery({
```
##########
src/components/page/ResourceListPage.tsx:
##########
@@ -0,0 +1,112 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 type { ProColumns } from '@ant-design/pro-components';
+import { ProTable } from '@ant-design/pro-components';
+import type { TablePaginationConfig } from 'antd';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { APISIXListResponse } from '@/types/schema/apisix/type';
+
+import PageHeader from './PageHeader';
+import { ToAddPageBtn } from './ToAddPageBtn';
+
+interface ResourceListPageProps<T> {
+ titleKey?: string;
+ columns: ProColumns<T>[];
+ queryHook: () => {
+ data?: APISIXListResponse<T> | undefined;
+ isLoading: boolean;
+ pagination: TablePaginationConfig | false;
+ refetch?: () => void;
+ };
+ rowKey: string;
+ addPageTo?: string;
+ resourceNameKey?: string;
+ emptyKey?: string;
+}
+
+const ResourceListPage = <T extends Record<string, unknown>>(
+ props: ResourceListPageProps<T>
+) => {
+ const {
+ titleKey,
+ columns,
+ queryHook,
+ rowKey,
+ addPageTo,
+ resourceNameKey,
+ emptyKey,
+ } = props;
+ const { t } = useTranslation();
+ const { data, isLoading, pagination } = queryHook();
+
+ const dataSource = useMemo(() => (data?.list as T[]) ?? [], [data]);
+ const total = pagination?.total ?? data?.total ?? 0;
+
+ const paginationConfig = useMemo(() => {
+ if (pagination === false) return false;
+
+ return {
+ current: pagination?.current ?? 1,
+ pageSize: pagination?.pageSize ?? 10,
+ total,
+ showSizeChanger: true,
+ pageSizeOptions: [10, 20, 50, 100],
+ hideOnSinglePage: false,
+ onChange: pagination?.onChange,
+ showTotal: (total: number, range: [number, number]) =>
+ `${range[0]}-${range[1]} of ${total} items`,
+ };
Review Comment:
The pagination configuration hardcodes `pageSizeOptions: [10, 20, 50, 100]` and `showTotal` format. While this provides consistency, it removes flexibility for pages that might need different pagination options. Consider making these configurable through props for edge cases where different pagination behavior is needed.
##########
src/routes/stream_routes/index.tsx:
##########
@@ -158,7 +128,4 @@ export const Route = createFileRoute('/stream_routes/')({
component: StreamRouteComponent,
errorComponent: StreamRoutesErrorComponent,
validateSearch: pageSearchSchema,
- loaderDeps: ({ search }) => search,
- loader: ({ deps }) =>
- queryClient.ensureQueryData(getStreamRouteListQueryOptions(deps)),
});
Review Comment:
The route loader (loaderDeps and loader) has been removed, which means data is no longer prefetched during route navigation. Combined with the switch from useSuspenseQuery to useQuery, this changes the loading behavior from suspense-based prefetch to on-demand fetch after component mount. This can cause a flash of loading state that wasn't present before and contradicts the PR description claim of unchanged behavior.
##########
src/types/schema/pageSearch.ts:
##########
@@ -19,17 +19,16 @@ import { z } from 'zod';
export const pageSearchSchema = z
.object({
- page: z
- .union([z.string(), z.number()])
- .optional()
- .default(1)
- .transform((val) => (val ? Number(val) : 1)),
- page_size: z
- .union([z.string(), z.number()])
- .optional()
- .default(10)
- .transform((val) => (val ? Number(val) : 10)),
+ page: z.preprocess(
+ (val) => (val === undefined || val === null ? undefined : Number(val)),
+ z.number().optional()
+ ),
+ page_size: z.preprocess(
+ (val) => (val === undefined || val === null ? undefined : Number(val)),
+ z.number().optional()
+ ),
Review Comment:
Removing default values for `page` and `page_size` in the schema means these values will be undefined if not provided in the URL. While the pagination config in ResourceListPage.tsx handles undefined with fallbacks (line 65-66: `pagination?.current ?? 1` and `pagination?.pageSize ?? 10`), this changes the URL behavior. Previously, navigating to `/services` would automatically add `?page=1&page_size=10` to the URL. Now these params won't appear unless explicitly set. This is a user-facing behavior change that contradicts the PR description.
##########
src/components/page/ResourceListPage.tsx:
##########
@@ -0,0 +1,112 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 type { ProColumns } from '@ant-design/pro-components';
+import { ProTable } from '@ant-design/pro-components';
+import type { TablePaginationConfig } from 'antd';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { APISIXListResponse } from '@/types/schema/apisix/type';
+
+import PageHeader from './PageHeader';
+import { ToAddPageBtn } from './ToAddPageBtn';
+
+interface ResourceListPageProps<T> {
+ titleKey?: string;
+ columns: ProColumns<T>[];
+ queryHook: () => {
+ data?: APISIXListResponse<T> | undefined;
+ isLoading: boolean;
+ pagination: TablePaginationConfig | false;
+ refetch?: () => void;
+ };
+ rowKey: string;
+ addPageTo?: string;
+ resourceNameKey?: string;
+ emptyKey?: string;
+}
+
+const ResourceListPage = <T extends Record<string, unknown>>(
+ props: ResourceListPageProps<T>
+) => {
+ const {
+ titleKey,
+ columns,
+ queryHook,
+ rowKey,
+ addPageTo,
+ resourceNameKey,
+ emptyKey,
+ } = props;
+ const { t } = useTranslation();
+ const { data, isLoading, pagination } = queryHook();
Review Comment:
The ResourceListPage component doesn't handle query errors. The original implementations with useSuspenseQuery would bubble errors to error boundaries. Now with useQuery, errors are silently ignored and the component will just show a loading state indefinitely if the query fails. Consider adding error handling logic or at least accessing `error` and `isError` from the query hook result to properly handle failed queries.
##########
e2e/tests/services.stream_routes.list.spec.ts:
##########
@@ -16,240 +16,245 @@
*/
import { servicesPom } from '@e2e/pom/services';
import { randomId } from '@e2e/utils/common';
+import { env } from '@e2e/utils/env';
import { e2eReq } from '@e2e/utils/req';
import { test } from '@e2e/utils/test';
import { uiGoto } from '@e2e/utils/ui';
-import { expect } from '@playwright/test';
+import { expect, type Page } from '@playwright/test';
-import { deleteAllServices, postServiceReq } from '@/apis/services';
-import {
- deleteAllStreamRoutes,
- postStreamRouteReq,
-} from '@/apis/stream_routes';
+import { postServiceReq } from '@/apis/services';
+import { postStreamRouteReq } from '@/apis/stream_routes';
test.describe.configure({ mode: 'serial' });
const serviceName = randomId('test-service');
const anotherServiceName = randomId('another-service');
+// Use indexed octets with random offset to ensure uniqueness (0-4 starting at random value to avoid reserved ranges)
+const randomOffset = Math.floor(Math.random() * 100) + 100;
+let octetIndex = randomOffset;
+const getUniqueOctet = () => (octetIndex++ % 256);
const streamRoutes = [
{
- server_addr: '127.0.0.1',
+ server_addr: `127.0.0.${getUniqueOctet()}`,
server_port: 8080,
},
{
- server_addr: '127.0.0.2',
+ server_addr: `127.0.0.${getUniqueOctet()}`,
server_port: 8081,
},
{
- server_addr: '127.0.0.3',
+ server_addr: `127.0.0.${getUniqueOctet()}`,
server_port: 8082,
},
];
-// Stream route that uses upstream directly instead of service_id
const upstreamStreamRoute = {
- server_addr: '127.0.0.40',
+ server_addr: `127.0.0.${getUniqueOctet()}`,
server_port: 9090,
upstream: {
nodes: [{ host: 'example.com', port: 80, weight: 100 }],
},
};
-// Stream route that belongs to another service
const anotherServiceStreamRoute = {
- server_addr: '127.0.0.20',
+ server_addr: `127.0.0.${getUniqueOctet()}`,
server_port: 9091,
};
let testServiceId: string;
let anotherServiceId: string;
const createdStreamRoutes: string[] = [];
-test.beforeAll(async () => {
- await deleteAllStreamRoutes(e2eReq);
- await deleteAllServices(e2eReq);
+let upstreamStreamRouteId: string;
+let anotherServiceStreamRouteId: string;
- // Create a test service for testing service stream routes
+test.beforeAll(async () => {
const serviceResponse = await postServiceReq(e2eReq, {
name: serviceName,
desc: 'Test service for stream route listing',
+ labels: { test: serviceName },
});
testServiceId = serviceResponse.data.value.id;
- // Create another service
const anotherServiceResponse = await postServiceReq(e2eReq, {
name: anotherServiceName,
desc: 'Another test service for stream route isolation testing',
+ labels: { test: anotherServiceName },
});
anotherServiceId = anotherServiceResponse.data.value.id;
- // Create test stream routes under the service
for (const streamRoute of streamRoutes) {
const streamRouteResponse = await postStreamRouteReq(e2eReq, {
server_addr: streamRoute.server_addr,
server_port: streamRoute.server_port,
service_id: testServiceId,
+ labels: { test: serviceName },
});
+ if (!streamRouteResponse.data?.value) {
+ throw new Error(`Failed to create stream route: ${JSON.stringify(streamRouteResponse.data)}`);
+ }
createdStreamRoutes.push(streamRouteResponse.data.value.id);
}
- // Create a stream route that uses upstream directly instead of service_id
- await postStreamRouteReq(e2eReq, upstreamStreamRoute);
+ const upstreamStreamRouteResponse = await postStreamRouteReq(e2eReq, {
+ ...upstreamStreamRoute,
+ labels: { test: 'upstream-' + serviceName },
+ });
+ if (!upstreamStreamRouteResponse.data?.value) {
+ throw new Error(`Failed to create upstream stream route: ${JSON.stringify(upstreamStreamRouteResponse.data)}`);
+ }
+ upstreamStreamRouteId = upstreamStreamRouteResponse.data.value.id;
- // Create a stream route under another service
- await postStreamRouteReq(e2eReq, {
+ const anotherServiceStreamRouteResponse = await postStreamRouteReq(e2eReq, {
...anotherServiceStreamRoute,
service_id: anotherServiceId,
+ labels: { test: anotherServiceName },
});
+ if (!anotherServiceStreamRouteResponse.data?.value) {
+ throw new Error(`Failed to create another service stream route: ${JSON.stringify(anotherServiceStreamRouteResponse.data)}`);
+ }
+ anotherServiceStreamRouteId = anotherServiceStreamRouteResponse.data.value.id;
+
+ // Significant delay for backend consistency in intensive parallel CI
+ // Moved to end of setup to ensure all resources have time to propagate
+ await new Promise((resolve) => setTimeout(resolve, 8000));
Review Comment:
An 8-second delay (8000ms) is added after test setup to ensure backend consistency. This significantly increases test execution time. Consider if this delay is truly necessary or if there's a more efficient way to ensure data propagation, such as polling for the resource to be available or using backend synchronization mechanisms.
##########
src/routes/stream_routes/index.tsx:
##########
@@ -100,37 +94,13 @@ export const StreamRouteList = (props: StreamRouteListProps) => {
}, [t, ToDetailBtn, refetch]);
return (
- <AntdConfigProvider>
- <ProTable
- columns={columns}
- dataSource={data.list}
- rowKey="id"
- loading={isLoading}
- search={false}
- options={false}
- pagination={pagination}
- cardProps={{ bodyStyle: { padding: 0 } }}
- toolbar={{
- menu: {
- type: 'inline',
- items: [
- {
- key: 'add',
- label: (
- <ToAddPageBtn
- key="add"
- label={t('info.add.title', {
- name: t('streamRoutes.singular'),
- })}
- to={`${routeKey}add`}
- />
- ),
- },
- ],
- },
- }}
- />
- </AntdConfigProvider>
+ <ResourceListPage
+ columns={columns}
+ queryHook={() => ({ data, isLoading, pagination, refetch })}
+ rowKey="id"
+ addPageTo={`${routeKey}add`}
+ resourceNameKey="streamRoutes.singular"
+ />
Review Comment:
The `titleKey` prop is not provided to ResourceListPage for stream routes, but it was not present in the original implementation either (no PageHeader was used). However, this creates inconsistency with other resource lists that do have titles (e.g., services, upstreams, etc.). Consider whether stream routes should also have a page title for consistency.
##########
src/types/schema/pageSearch.ts:
##########
@@ -19,17 +19,16 @@ import { z } from 'zod';
export const pageSearchSchema = z
.object({
- page: z
- .union([z.string(), z.number()])
- .optional()
- .default(1)
- .transform((val) => (val ? Number(val) : 1)),
- page_size: z
- .union([z.string(), z.number()])
- .optional()
- .default(10)
- .transform((val) => (val ? Number(val) : 10)),
+ page: z.preprocess(
+ (val) => (val === undefined || val === null ? undefined : Number(val)),
+ z.number().optional()
+ ),
+ page_size: z.preprocess(
+ (val) => (val === undefined || val === null ? undefined : Number(val)),
+ z.number().optional()
+ ),
name: z.string().optional(),
+ search: z.string().optional(),
Review Comment:
The E2E tests are using a `search` parameter (line 186 in services.stream_routes.list.spec.ts, line 192 in services.routes.list.spec.ts), which is added to pageSearchSchema.ts but not actually implemented in the UI or API integration. The tests set this parameter but there's no evidence it's being used for filtering. This could lead to false test passes if the tests rely on this filtering working.
##########
src/types/schema/pageSearch.ts:
##########
@@ -19,17 +19,16 @@ import { z } from 'zod';
export const pageSearchSchema = z
.object({
- page: z
- .union([z.string(), z.number()])
- .optional()
- .default(1)
- .transform((val) => (val ? Number(val) : 1)),
- page_size: z
- .union([z.string(), z.number()])
- .optional()
- .default(10)
- .transform((val) => (val ? Number(val) : 10)),
+ page: z.preprocess(
+ (val) => (val === undefined || val === null ? undefined : Number(val)),
+ z.number().optional()
+ ),
+ page_size: z.preprocess(
+ (val) => (val === undefined || val === null ? undefined : Number(val)),
+ z.number().optional()
+ ),
name: z.string().optional(),
+ search: z.string().optional(),
Review Comment:
A new `search` field has been added to the page search schema, but this field is not used in any of the refactored components. This appears to be prepared for future functionality but is not documented or utilized. Either remove this unused field or document its intended purpose.
##########
e2e/utils/test.ts:
##########
@@ -43,31 +48,46 @@ export const test = baseTest.extend<object, { workerStorageState: string }>({
return use(fileName);
}
- const page = await browser.newPage({ storageState: undefined });
+ try {
+ const page = await browser.newPage({ storageState: undefined });
+
+ // have to use env here, because the baseURL is not available in worker
+ await page.goto(env.E2E_TARGET_URL, { waitUntil: 'load' });
+
+ // we need to authenticate
+ const settingsModal = page.getByRole('dialog', { name: 'Settings' });
+ await expect(settingsModal).toBeVisible({ timeout: 30000 });
+ // PasswordInput renders with a label, use getByLabel instead
+ const adminKeyInput = page.getByLabel('Admin Key');
+ await adminKeyInput.clear();
+ await adminKeyInput.fill(adminKey);
+
+ const closeButton = page
+ .getByRole('dialog', { name: 'Settings' })
+ .getByRole('button');
+ await expect(closeButton).toBeVisible({ timeout: 10000 });
+ await closeButton.click();
- // have to use env here, because the baseURL is not available in worker
- await page.goto(env.E2E_TARGET_URL);
+ // Wait for auth to complete
+ await expect(settingsModal).toBeHidden({ timeout: 15000 });
- // we need to authenticate
- const settingsModal = page.getByRole('dialog', { name: 'Settings' });
- await expect(settingsModal).toBeVisible();
- // PasswordInput renders with a label, use getByLabel instead
- const adminKeyInput = page.getByLabel('Admin Key');
- await adminKeyInput.clear();
- await adminKeyInput.fill(adminKey);
- await page
- .getByRole('dialog', { name: 'Settings' })
- .getByRole('button')
- .click();
+ // Wait for any post-auth navigation/loading to complete
+ await page.waitForLoadState('load');
+
+ await page.context().storageState({ path: fileName });
+ await page.close();
+ } catch (error) {
+ console.error(`Failed to authenticate worker ${id}:`, error);
+ throw error;
+ }
- await page.context().storageState({ path: fileName });
- await page.close();
await use(fileName);
},
{ scope: 'worker' },
],
page: async ({ baseURL, page }, use) => {
- await page.goto(baseURL);
+ await page.goto(baseURL ?? '');
Review Comment:
The baseURL can now be an empty string if undefined. This could cause navigation issues if baseURL is not properly configured. Consider using a fallback or validation: `await page.goto(baseURL ?? env.E2E_TARGET_URL);` to ensure a valid URL is always used.
```suggestion
await page.goto(baseURL && baseURL.length > 0 ? baseURL : env.E2E_TARGET_URL);
```
##########
e2e/utils/req.ts:
##########
@@ -27,27 +27,39 @@ export const getPlaywrightRequestAdapter = (
ctx: APIRequestContext
): AxiosAdapter => {
return async (config) => {
- const { url, data, baseURL } = config;
+ const { url, data, baseURL, method } = config;
if (typeof url === 'undefined') {
throw new Error('Need to provide a url');
}
type Payload = Parameters<APIRequestContext['fetch']>[1];
const payload: Payload = {
headers: config.headers,
- method: config.method,
- failOnStatusCode: true,
+ method,
+ failOnStatusCode: false,
data,
};
const urlWithBase = `${baseURL}${url}`;
const res = await ctx.fetch(urlWithBase, payload);
+ const status = res.status();
+
+ // Idempotent DELETE: Treat 404 as 200 OK
+ if (method?.toLowerCase() === 'delete' && status === 404) {
+ return {
+ data: {},
+ status: 200,
+ statusText: 'OK',
+ headers: {},
+ config,
+ };
+ }
Review Comment:
Good improvement for test stability! Treating DELETE 404 as success makes tests more robust to timing issues and parallel execution. However, this silent handling could mask actual issues where a resource should exist but doesn't. Consider adding a warning log when this occurs, or document this behavior clearly in tests to avoid confusion.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#discussion_r2896983272
##########
e2e/utils/req.ts:
##########
@@ -27,30 +27,66 @@ export const getPlaywrightRequestAdapter = (
ctx: APIRequestContext
): AxiosAdapter => {
return async (config) => {
- const { url, data, baseURL } = config;
+ const { url, data, baseURL, method } = config;
if (typeof url === 'undefined') {
throw new Error('Need to provide a url');
}
type Payload = Parameters<APIRequestContext['fetch']>[1];
const payload: Payload = {
headers: config.headers,
- method: config.method,
- failOnStatusCode: true,
+ method,
+ failOnStatusCode: false,
data,
};
const urlWithBase = `${baseURL}${url}`;
const res = await ctx.fetch(urlWithBase, payload);
+ const status = res.status();
- try {
+ // Idempotent DELETE: Treat 404 as 200 OK
+ if (method?.toLowerCase() === 'delete' && status === 404) {
+ console.warn(`[e2eReq] Ignored 404 on DELETE for ${urlWithBase}, treating as 200 OK.`);
return {
+ data: {},
+ status: 200,
+ statusText: 'OK',
+ headers: {},
+ config,
+ };
+ }
Review Comment:
In the idempotent DELETE branch (404 treated as OK), the Playwright APIResponse (`res`) is returned without being disposed. This bypasses the `finally { await res.dispose(); }` and can leak resources/handles across the test run. Dispose the response before returning (or restructure to keep all returns inside the try/finally).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#discussion_r2893223739
##########
e2e/server/apisix_conf.yml:
##########
@@ -1,42 +1,22 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You 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.
-#
-
apisix:
- node_listen: 9080 # APISIX listening port
+ node_listen: 9080
enable_ipv6: false
proxy_mode: http&stream
stream_proxy:
Review Comment:
The Apache license header comment block was removed from this YAML file. If this repo requires ASF headers on source/config files (as seen in other e2e/server YAMLs), please restore the license header to keep licensing compliance consistent.
##########
e2e/tests/services.stream_routes.list.spec.ts:
##########
@@ -16,240 +16,231 @@
*/
import { servicesPom } from '@e2e/pom/services';
import { randomId } from '@e2e/utils/common';
+import { env } from '@e2e/utils/env';
import { e2eReq } from '@e2e/utils/req';
import { test } from '@e2e/utils/test';
import { uiGoto } from '@e2e/utils/ui';
-import { expect } from '@playwright/test';
+import { expect, type Page } from '@playwright/test';
Review Comment:
`env` is imported but never used in this spec file. This will fail lint/typecheck with unused-import rules; please remove the import (or use it if intended).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Baluduvamsi2006 (via GitHub)" <gi...@apache.org>.
Baluduvamsi2006 commented on PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#issuecomment-3976939836
@YSC9999 can you request a review from copilot
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#discussion_r2866880694
##########
src/routes/services/index.tsx:
##########
@@ -90,60 +87,18 @@ const ServiceList = () => {
}, [t, refetch]);
return (
- <AntdConfigProvider>
- <ProTable
- locale={{
- emptyText: (
- <Empty
- description={t('services.empty')}
- image={Empty.PRESENTED_IMAGE_SIMPLE}
- />
- ),
- }}
- columns={columns}
- dataSource={data.list}
- rowKey="id"
- loading={isLoading}
- search={false}
- options={false}
- pagination={pagination}
- cardProps={{ bodyStyle: { padding: 0 } }}
- toolbar={{
- menu: {
- type: 'inline',
- items: [
- {
- key: 'add',
- label: (
- <ToAddPageBtn
- key="add"
- label={t('info.add.title', {
- name: t('services.singular'),
- })}
- to="/services/add"
- />
- ),
- },
- ],
- },
- }}
- />
- </AntdConfigProvider>
+ <ResourceListPage
+ titleKey="sources.services"
+ columns={columns}
+ queryData={{ data, isLoading, pagination, refetch }}
+ rowKey="id"
+ addPageTo="/services/add"
+ resourceNameKey="services.singular"
+ emptyKey="services.empty"
+ />
);
Review Comment:
`ResourceListPage`'s `emptyKey` handling only renders translated text, but the Services list previously rendered a richer `<Empty />` state (description + simple image). If the goal is 1:1 UI preservation, consider extending `ResourceListPage` to accept a custom `emptyText` ReactNode (or a render prop) so pages like Services can keep the existing Empty component presentation.
##########
src/components/page/ResourceListPage.tsx:
##########
@@ -0,0 +1,116 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 type { ProColumns } from '@ant-design/pro-components';
+import { ProTable } from '@ant-design/pro-components';
+import type { TablePaginationConfig } from 'antd';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { AntdConfigProvider } from '@/config/antdConfigProvider';
+
+import PageHeader from './PageHeader';
+import { ToAddPageBtn } from './ToAddPageBtn';
+
+interface ResourceListPageProps<T> {
+ titleKey?: string;
+ columns: ProColumns<T>[];
+ queryData: {
+ data?: { list: T[]; total: number;[key: string]: unknown } | undefined;
+ isLoading: boolean;
+ pagination: TablePaginationConfig | false;
+ refetch?: () => void;
+ };
+ rowKey: string;
+ addPageTo?: string;
+ resourceNameKey?: string;
+ emptyKey?: string;
+ pageSizeOptions?: number[] | string[];
+ showTotal?: (total: number, range: [number, number]) => React.ReactNode;
+}
+
+const ResourceListPage = <T extends Record<string, unknown>>(
+ props: ResourceListPageProps<T>
+) => {
+ const {
+ titleKey,
+ columns,
+ queryData,
+ rowKey,
+ addPageTo,
+ resourceNameKey,
+ emptyKey,
+ pageSizeOptions,
+ showTotal: customShowTotal,
+ } = props;
+ const { t } = useTranslation();
+ const { data, isLoading, pagination } = queryData;
+
+ const dataSource = useMemo(() => (data?.list as unknown as T[]) ?? [], [data]);
+ const total = (pagination !== false ? pagination?.total : undefined) ?? data?.total ?? 0;
+
+ const paginationConfig = useMemo(() => {
+ if (pagination === false) return false;
+
+ return {
+ current: pagination?.current ?? 1,
+ pageSize: pagination?.pageSize ?? 10,
+ total,
+ showSizeChanger: true,
+ pageSizeOptions: pageSizeOptions ?? [10, 20, 50, 100],
+ hideOnSinglePage: false,
+ onChange: pagination?.onChange,
+ showTotal: customShowTotal ?? ((total: number, range: [number, number]) =>
+ `${range[0]}-${range[1]} of ${total} items`),
+ };
Review Comment:
`ResourceListPage` sets a default `showTotal` renderer (and hardcodes the text in English). This changes pagination UI compared to AntD/ProTable defaults and bypasses i18n. To preserve existing behavior, only pass `showTotal` when the caller explicitly provides it (or derive it from an i18n key).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#discussion_r2896660197
##########
src/components/page/ResourceListPage.tsx:
##########
@@ -0,0 +1,140 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 type { ProColumns } from '@ant-design/pro-components';
+import { ProTable } from '@ant-design/pro-components';
+import type { TablePaginationConfig } from 'antd';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { AntdConfigProvider } from '@/config/antdConfigProvider';
+
+import PageHeader from './PageHeader';
+import type { ToAddPageBtnProps } from './ToAddPageBtn';
+import { ToAddPageBtn } from './ToAddPageBtn';
+
+interface ResourceListPageProps<T> {
+ titleKey?: string;
+ columns: ProColumns<T>[];
+ queryData: {
+ data?: { list: T[]; total: number } | undefined;
+ isLoading: boolean;
+ pagination: TablePaginationConfig | false;
+ refetch?: () => void;
+ };
+ rowKey: string | ((record: T) => string);
+ addPageTo?: ToAddPageBtnProps['to'];
+ resourceNameKey?: string;
+ emptyText?: React.ReactNode;
+ pageSizeOptions?: number[] | string[];
+ showTotal?: (total: number, range: [number, number]) => React.ReactNode;
+}
+
+function isRecord(val: unknown): val is Record<string, unknown> {
+ return val !== null && typeof val === 'object' && !Array.isArray(val);
+}
+
+const ResourceListPage = <T extends Record<string, unknown>>(
+ props: ResourceListPageProps<T>,
+) => {
+ const {
+ titleKey,
+ columns,
+ queryData,
+ rowKey,
+ addPageTo,
+ resourceNameKey,
+ emptyText,
+ pageSizeOptions,
+ showTotal: customShowTotal,
+ } = props;
+ const { t } = useTranslation();
+ const { data, isLoading, pagination } = queryData;
+
+ const dataSource = useMemo(() => data?.list ?? [], [data]);
+ const total =
+ (pagination !== false ? pagination?.total : undefined) ?? data?.total ?? 0;
+
+ const paginationConfig = useMemo(() => {
+ if (pagination === false) return false;
+
+ return {
+ current: pagination?.current ?? 1,
+ pageSize: pagination?.pageSize ?? 10,
+ total,
+ showSizeChanger: true,
+ pageSizeOptions: pageSizeOptions ?? [10, 20, 50, 100],
+ hideOnSinglePage: false,
+ onChange: pagination?.onChange,
+ ...(customShowTotal ? { showTotal: customShowTotal } : {}),
+ };
+ }, [pagination, total, pageSizeOptions, customShowTotal]);
+
+ const resolvedRowKey = useMemo(
+ () =>
+ typeof rowKey === 'function'
+ ? rowKey
+ : (record: T) => {
+ // APISIX list items wrap data in a `value` property
+ const raw = record['value'];
+ const value = isRecord(raw) ? raw : undefined;
+ return String(value?.[rowKey] ?? record[rowKey] ?? '');
Review Comment:
The `resolvedRowKey` fallback returns an empty string when the requested key is missing (`String(... ?? '')`). This can lead to duplicate React keys (all rows share "") and unstable table rendering. Since APISIX list items include a stable `key` field on the wrapper object, consider falling back to `record.key` (or another guaranteed unique field) instead of `''` when neither `value[rowKey]` nor `record[rowKey]` exists.
##########
e2e/utils/req.ts:
##########
@@ -27,27 +27,49 @@ export const getPlaywrightRequestAdapter = (
ctx: APIRequestContext
): AxiosAdapter => {
return async (config) => {
- const { url, data, baseURL } = config;
+ const { url, data, baseURL, method } = config;
if (typeof url === 'undefined') {
throw new Error('Need to provide a url');
}
type Payload = Parameters<APIRequestContext['fetch']>[1];
const payload: Payload = {
headers: config.headers,
- method: config.method,
- failOnStatusCode: true,
+ method,
+ failOnStatusCode: false,
data,
};
const urlWithBase = `${baseURL}${url}`;
const res = await ctx.fetch(urlWithBase, payload);
+ const status = res.status();
+
+ // Idempotent DELETE: Treat 404 as 200 OK
+ if (method?.toLowerCase() === 'delete' && status === 404) {
+ console.warn(`[e2eReq] Ignored 404 on DELETE for ${urlWithBase}, treating as 200 OK.`);
+ return {
+ data: {},
+ status: 200,
+ statusText: 'OK',
+ headers: {},
+ config,
+ };
+ }
try {
+ let responseData = {};
+ try {
+ responseData = await res.json();
+ } catch {
+ // ignore JSON parse errors on empty or text responses
+ }
+ if (config.validateStatus && !config.validateStatus(status)) {
+ throw new Error(`Request failed with status code ${status}`);
+ }
Review Comment:
The manual `validateStatus` check will almost always run (Axios populates `config.validateStatus` from defaults) and throws a plain `Error` for non-2xx responses. This bypasses Axios's normal `settle()` behavior, so callers won’t receive an `AxiosError` with `response/status` attached, making failures harder to debug and potentially breaking code that relies on AxiosError shape. Recommend removing this manual check and letting Axios handle status validation based on `validateStatus`, while keeping `failOnStatusCode: false` in Playwright fetch.
```suggestion
```
##########
src/types/schema/pageSearch.ts:
##########
@@ -19,16 +19,14 @@ import { z } from 'zod';
export const pageSearchSchema = z
.object({
- page: z
- .union([z.string(), z.number()])
- .optional()
- .default(1)
- .transform((val) => (val ? Number(val) : 1)),
- page_size: z
- .union([z.string(), z.number()])
- .optional()
- .default(10)
- .transform((val) => (val ? Number(val) : 10)),
+ page: z.preprocess(
+ (val) => (val === undefined || val === null || val === '' ? undefined : Number(val)),
+ z.number().int().min(1).optional().default(1)
+ ),
Review Comment:
`pageSearchSchema` now enforces `int().min(1)` and will throw on `page=0`, negative values, or non-numeric strings (because `Number(val)` becomes `NaN`). Since this schema is used by TanStack Router `validateSearch` and also re-parsed in `useTablePagination`, malformed URLs can now hard-fail the route instead of falling back to defaults. To preserve prior behavior, consider coercing invalid/NaN/<=0 values to `undefined` in the preprocess (so `.default(1)` applies) rather than rejecting them (apply the same approach to `page_size`).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#discussion_r2893187568
##########
e2e/tests/services.stream_routes.list.spec.ts:
##########
@@ -16,240 +16,231 @@
*/
import { servicesPom } from '@e2e/pom/services';
import { randomId } from '@e2e/utils/common';
+import { env } from '@e2e/utils/env';
import { e2eReq } from '@e2e/utils/req';
import { test } from '@e2e/utils/test';
import { uiGoto } from '@e2e/utils/ui';
-import { expect } from '@playwright/test';
+import { expect, type Page } from '@playwright/test';
-import { deleteAllServices, postServiceReq } from '@/apis/services';
-import {
- deleteAllStreamRoutes,
- postStreamRouteReq,
-} from '@/apis/stream_routes';
+import { postServiceReq } from '@/apis/services';
+import { getStreamRouteListReq, postStreamRouteReq } from '@/apis/stream_routes';
test.describe.configure({ mode: 'serial' });
const serviceName = randomId('test-service');
const anotherServiceName = randomId('another-service');
+// Use indexed octets with random offset to ensure uniqueness (0-4 starting at random value to avoid reserved ranges)
+const randomOffset = Math.floor(Math.random() * 100) + 100;
+let octetIndex = randomOffset;
+const getUniqueOctet = () => (octetIndex++ % 256);
const streamRoutes = [
{
- server_addr: '127.0.0.1',
+ server_addr: `127.0.0.${getUniqueOctet()}`,
server_port: 8080,
},
{
- server_addr: '127.0.0.2',
+ server_addr: `127.0.0.${getUniqueOctet()}`,
server_port: 8081,
},
{
- server_addr: '127.0.0.3',
+ server_addr: `127.0.0.${getUniqueOctet()}`,
server_port: 8082,
},
];
-// Stream route that uses upstream directly instead of service_id
const upstreamStreamRoute = {
- server_addr: '127.0.0.40',
+ server_addr: `127.0.0.${getUniqueOctet()}`,
server_port: 9090,
upstream: {
nodes: [{ host: 'example.com', port: 80, weight: 100 }],
},
};
-// Stream route that belongs to another service
const anotherServiceStreamRoute = {
- server_addr: '127.0.0.20',
+ server_addr: `127.0.0.${getUniqueOctet()}`,
server_port: 9091,
};
let testServiceId: string;
let anotherServiceId: string;
const createdStreamRoutes: string[] = [];
-test.beforeAll(async () => {
- await deleteAllStreamRoutes(e2eReq);
- await deleteAllServices(e2eReq);
+let upstreamStreamRouteId: string;
+let anotherServiceStreamRouteId: string;
- // Create a test service for testing service stream routes
+test.beforeAll(async () => {
const serviceResponse = await postServiceReq(e2eReq, {
name: serviceName,
desc: 'Test service for stream route listing',
+ labels: { test: serviceName },
});
testServiceId = serviceResponse.data.value.id;
- // Create another service
const anotherServiceResponse = await postServiceReq(e2eReq, {
name: anotherServiceName,
desc: 'Another test service for stream route isolation testing',
+ labels: { test: anotherServiceName },
});
anotherServiceId = anotherServiceResponse.data.value.id;
- // Create test stream routes under the service
for (const streamRoute of streamRoutes) {
const streamRouteResponse = await postStreamRouteReq(e2eReq, {
server_addr: streamRoute.server_addr,
server_port: streamRoute.server_port,
service_id: testServiceId,
+ labels: { test: serviceName },
});
+ if (!streamRouteResponse.data?.value) {
+ throw new Error(`Failed to create stream route: ${JSON.stringify(streamRouteResponse.data)}`);
+ }
createdStreamRoutes.push(streamRouteResponse.data.value.id);
}
- // Create a stream route that uses upstream directly instead of service_id
- await postStreamRouteReq(e2eReq, upstreamStreamRoute);
+ const upstreamStreamRouteResponse = await postStreamRouteReq(e2eReq, {
+ ...upstreamStreamRoute,
+ labels: { test: 'upstream-' + serviceName },
+ });
+ if (!upstreamStreamRouteResponse.data?.value) {
+ throw new Error(`Failed to create upstream stream route: ${JSON.stringify(upstreamStreamRouteResponse.data)}`);
+ }
+ upstreamStreamRouteId = upstreamStreamRouteResponse.data.value.id;
- // Create a stream route under another service
- await postStreamRouteReq(e2eReq, {
+ const anotherServiceStreamRouteResponse = await postStreamRouteReq(e2eReq, {
...anotherServiceStreamRoute,
service_id: anotherServiceId,
+ labels: { test: anotherServiceName },
});
+ if (!anotherServiceStreamRouteResponse.data?.value) {
+ throw new Error(`Failed to create another service stream route: ${JSON.stringify(anotherServiceStreamRouteResponse.data)}`);
+ }
+ anotherServiceStreamRouteId = anotherServiceStreamRouteResponse.data.value.id;
+
+ // Wait for data propagation to complete by polling the backend
+ await expect(async () => {
+ const res = await getStreamRouteListReq(e2eReq, { page_size: 100 } as Parameters<typeof getStreamRouteListReq>[1]);
+ const existingIds = res.list.map((r) => r.value.id);
+ const expectedIds = [...createdStreamRoutes, upstreamStreamRouteId, anotherServiceStreamRouteId].filter(Boolean);
+ expect(expectedIds.every((id) => existingIds.includes(id))).toBeTruthy();
+ }).toPass({ timeout: 15000, intervals: [1000] });
});
test.afterAll(async () => {
- await deleteAllStreamRoutes(e2eReq);
- await deleteAllServices(e2eReq);
+ const allStreamRouteIds = [...createdStreamRoutes, upstreamStreamRouteId, anotherServiceStreamRouteId].filter(Boolean);
+ for (const id of allStreamRouteIds) {
+ await e2eReq.delete(`/stream_routes/${id}`);
+ }
+
+ if (testServiceId) {
+ await e2eReq.delete(`/services/${testServiceId}`);
+ }
+ if (anotherServiceId) {
+ await e2eReq.delete(`/services/${anotherServiceId}`);
+ }
});
-test('should only show stream routes with current service_id', async ({
- page,
-}) => {
- await test.step('should only show stream routes with current service_id', async () => {
- await servicesPom.toIndex(page);
- await servicesPom.isIndexPage(page);
+async function navigateToServiceDetail(page: Page, id: string) {
+ await uiGoto(page, '/services/detail/$id', { id });
+ await page.waitForLoadState('load');
+ await servicesPom.isDetailPage(page);
+}
- await page
- .getByRole('row', { name: serviceName })
- .getByRole('button', { name: 'View' })
- .click();
- await servicesPom.isDetailPage(page);
+test('should only show stream routes with current service_id', async ({ page }) => {
+ await test.step('should only show stream routes with current service_id', async () => {
+ await navigateToServiceDetail(page, testServiceId);
await servicesPom.getServiceStreamRoutesTab(page).click();
await servicesPom.isServiceStreamRoutesPage(page);
+ await page.waitForLoadState('load');
+
+ await expect(page.getByRole('cell', { name: anotherServiceStreamRoute.server_addr })).toBeHidden();
+ await expect(page.getByRole('cell', { name: upstreamStreamRoute.server_addr })).toBeHidden();
- // Stream routes from another service should not be visible
- await expect(
- page.getByRole('cell', { name: anotherServiceStreamRoute.server_addr })
- ).toBeHidden();
- // Upstream stream route (without service_id) should not be visible
- await expect(
- page.getByRole('cell', { name: upstreamStreamRoute.server_addr })
- ).toBeHidden();
- // Only stream routes belonging to current service should be visible
for (const streamRoute of streamRoutes) {
- await expect(
- page.getByRole('cell', { name: streamRoute.server_addr })
- ).toBeVisible();
+ await expect(page.getByRole('cell', { name: streamRoute.server_addr })).toBeVisible({ timeout: 30000 });
}
});
await test.step('without service_id stream routes should still exist in the stream routes list', async () => {
- await uiGoto(page, '/stream_routes');
- await expect(page).toHaveURL((url) =>
- url.pathname.endsWith('/stream_routes')
- );
- const title = page.getByRole('heading', { name: 'Stream Routes' });
- await expect(title).toBeVisible();
-
- // All stream routes should be visible in the global stream routes list
- await expect(
- page.getByRole('cell', { name: upstreamStreamRoute.server_addr })
- ).toBeVisible();
- await expect(
- page.getByRole('cell', { name: anotherServiceStreamRoute.server_addr })
- ).toBeVisible();
+ // Navigate using POM to reach the correct base path
+ await page.goto(`${env.E2E_TARGET_URL}stream_routes`);
Review Comment:
`page.goto(`${env.E2E_TARGET_URL}stream_routes`)` assumes `E2E_TARGET_URL` always ends with a trailing slash. If someone overrides the env var without the trailing `/`, this produces an invalid URL (e.g. `.../apisixstream_routes`). Use `uiGoto(page, '/stream_routes')`, `new URL('stream_routes', env.E2E_TARGET_URL)`, or otherwise ensure exactly one `/` between base and path.
```suggestion
await uiGoto(page, '/stream_routes');
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Baluduvamsi2006 (via GitHub)" <gi...@apache.org>.
Baluduvamsi2006 commented on PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#issuecomment-3976703467
<img width="1919" height="1063" alt="image" src="https://github.com/user-attachments/assets/adeb0f6c-c7a7-4bbc-8f51-7ec5e38561bb" />
@Baoyuantop test(e2e): ✨ The promised land: 93/93 tests passing flawlessly
Banished the silent timeouts, tamed the Monaco Editor race conditions, and forced Ant Design tables to correctly log inputs before clicking submit. Playwright suite is officially 100% green and completely stable! ✅
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#discussion_r2897247942
##########
src/components/page/ResourceListPage.tsx:
##########
@@ -0,0 +1,140 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 type { ProColumns } from '@ant-design/pro-components';
+import { ProTable } from '@ant-design/pro-components';
+import type { TablePaginationConfig } from 'antd';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { AntdConfigProvider } from '@/config/antdConfigProvider';
+
+import PageHeader from './PageHeader';
+import type { ToAddPageBtnProps } from './ToAddPageBtn';
+import { ToAddPageBtn } from './ToAddPageBtn';
+
+interface ResourceListPageProps<T> {
+ titleKey?: string;
+ columns: ProColumns<T>[];
+ queryData: {
+ data?: { list: T[]; total: number } | undefined;
+ isLoading: boolean;
+ pagination: TablePaginationConfig | false;
+ refetch?: () => void;
+ };
+ rowKey: string | ((record: T) => string);
+ addPageTo?: ToAddPageBtnProps['to'];
+ resourceNameKey?: string;
+ emptyText?: React.ReactNode;
+ pageSizeOptions?: number[] | string[];
+ showTotal?: (total: number, range: [number, number]) => React.ReactNode;
+}
+
+function isRecord(val: unknown): val is Record<string, unknown> {
+ return val !== null && typeof val === 'object' && !Array.isArray(val);
+}
+
+const ResourceListPage = <T extends Record<string, unknown>>(
+ props: ResourceListPageProps<T>,
+) => {
+ const {
+ titleKey,
+ columns,
+ queryData,
+ rowKey,
+ addPageTo,
+ resourceNameKey,
+ emptyText,
+ pageSizeOptions,
+ showTotal: customShowTotal,
+ } = props;
+ const { t } = useTranslation();
+ const { data, isLoading, pagination } = queryData;
+
+ const dataSource = useMemo(() => data?.list ?? [], [data]);
+ const total =
+ (pagination !== false ? pagination?.total : undefined) ?? data?.total ?? 0;
+
+ const paginationConfig = useMemo(() => {
+ if (pagination === false) return false;
+
+ return {
+ current: pagination?.current ?? 1,
+ pageSize: pagination?.pageSize ?? 10,
+ total,
+ showSizeChanger: true,
+ pageSizeOptions: pageSizeOptions ?? [10, 20, 50, 100],
+ hideOnSinglePage: false,
+ onChange: pagination?.onChange,
+ ...(customShowTotal ? { showTotal: customShowTotal } : {}),
+ };
+ }, [pagination, total, pageSizeOptions, customShowTotal]);
+
+ const resolvedRowKey = useMemo(
+ () =>
+ typeof rowKey === 'function'
+ ? rowKey
+ : (record: T) => {
+ // APISIX list items wrap data in a `value` property
+ const raw = record['value'];
+ const value = isRecord(raw) ? raw : undefined;
+ return String(value?.[rowKey] ?? record[rowKey] ?? record['key'] ?? '');
+ },
Review Comment:
`resolvedRowKey` falls back to `''` when it can’t find `value[rowKey]`, `record[rowKey]`, or `record.key`. If that happens, multiple rows will share the same key, which can cause React key warnings and unstable row rendering. Consider using the `index` argument of the rowKey function as a final fallback (or throwing/logging when a key can’t be resolved) to ensure a stable, unique key per row.
##########
src/routes/services/detail.$id/stream_routes/index.tsx:
##########
@@ -55,6 +50,8 @@ export const Route = createFileRoute('/services/detail/$id/stream_routes/')({
errorComponent: StreamRoutesErrorComponent,
validateSearch: pageSearchSchema,
loaderDeps: ({ search }) => search,
- loader: ({ deps }) =>
- queryClient.ensureQueryData(getStreamRouteListQueryOptions(deps)),
-});
+ loader: ({ deps, params: { id } }) =>
+ queryClient.ensureQueryData(
+ getStreamRouteListQueryOptions({ ...deps, filter: { service_id: id } }),
+ ),
Review Comment:
The route loader overwrites any existing `deps.filter` by setting `filter: { service_id: id }`. Since `pageSearchSchema` is `.passthrough()`, additional filter fields could be present in `deps` and would be lost during prefetching; this can also create a mismatch between loader-prefetched data and what `useStreamRouteList(..., defaultParams)` fetches. Consider merging with any existing filter while still enforcing `service_id`.
##########
package.json:
##########
@@ -102,11 +102,12 @@
"overrides": {
"lodash": ">=4.17.21",
"minimatch": ">=3.0.5",
- "@swc/core": "1.10.0"
+ "@swc/core": "1.10.0",
+ "@iconify/utils": "2.1.33"
},
Review Comment:
`pnpm.overrides` forces `@iconify/utils` to `2.1.33`, while `unplugin-icons` is being installed with that downgraded version (see pnpm-lock entry for `unplugin-icons@22.5.0`). Since this is a major-version downgrade, it risks runtime/build incompatibilities in the Vite icons plugin. If this pin is required (e.g., for a security advisory), consider adding a brief rationale (and/or a compatibility note) and ensure it’s aligned with `unplugin-icons`’ expected `@iconify/utils` major version.
##########
src/routes/services/detail.$id/routes/index.tsx:
##########
@@ -15,44 +15,41 @@
* limitations under the License.
*/
import { createFileRoute, useParams } from '@tanstack/react-router';
-import { useTranslation } from 'react-i18next';
import { getRouteListQueryOptions } from '@/apis/hooks';
-import PageHeader from '@/components/page/PageHeader';
import { ToDetailPageBtn } from '@/components/page/ToAddPageBtn';
import { queryClient } from '@/config/global';
import { RouteList } from '@/routes/routes';
import { pageSearchSchema } from '@/types/schema/pageSearch';
function RouteComponent() {
- const { t } = useTranslation();
const { id } = useParams({ from: '/services/detail/$id/routes/' });
return (
- <>
- <PageHeader title={t('sources.routes')} />
- <RouteList
- routeKey="/services/detail/$id/routes/"
- defaultParams={{
- filter: {
- service_id: id,
- },
- }}
- ToDetailBtn={({ record }) => (
- <ToDetailPageBtn
- key="detail"
- to="/services/detail/$id/routes/detail/$routeId"
- params={{ id, routeId: record.value.id }}
- />
- )}
- />
- </>
+ <RouteList
+ titleKey="sources.routes"
+ routeKey="/services/detail/$id/routes/"
+ defaultParams={{
+ filter: {
+ service_id: id,
+ },
+ }}
+ ToDetailBtn={({ record }) => (
+ <ToDetailPageBtn
+ key="detail"
+ to="/services/detail/$id/routes/detail/$routeId"
+ params={{ id, routeId: record.value.id }}
+ />
+ )}
+ />
);
}
export const Route = createFileRoute('/services/detail/$id/routes/')({
component: RouteComponent,
validateSearch: pageSearchSchema,
loaderDeps: ({ search }) => search,
- loader: ({ deps }) =>
- queryClient.ensureQueryData(getRouteListQueryOptions(deps)),
-});
+ loader: ({ deps, params: { id } }) =>
+ queryClient.ensureQueryData(
+ getRouteListQueryOptions({ ...deps, filter: { service_id: id } }),
+ ),
Review Comment:
The route loader overwrites any existing `deps.filter` by setting `filter: { service_id: id }`. If other filter fields are ever added/passed via the URL (pageSearchSchema is `.passthrough()`), they’ll be dropped for prefetching, and loader-prefetched data can diverge from what the list hook fetches. Prefer merging with any existing filter (e.g., preserve `deps.filter` while enforcing `service_id`).
##########
e2e/utils/test.ts:
##########
@@ -24,50 +24,87 @@ import { env } from './env';
export type Test = typeof test;
export const test = baseTest.extend<object, { workerStorageState: string }>({
- storageState: ({ workerStorageState }, use) => use(workerStorageState),
+ storageState: ({ workerStorageState }, use) => {
+ // If storageState file doesn't exist yet, use undefined to skip loading it
+ // Playwright will still save it after tests run if needed
+ return use(workerStorageState);
+ },
Review Comment:
The comment says the fixture will use `undefined` storageState if the auth file doesn’t exist yet, but the implementation always passes `workerStorageState` to `use(...)`. Either update the comment to match current behavior or add the existence check if skipping storageState loading is intended.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#discussion_r2897365758
##########
src/apis/upstreams.ts:
##########
@@ -76,7 +76,13 @@ export const deleteAllUpstreams = async (req: AxiosInstance) => {
res.list.map((d) =>
req.delete(`${API_UPSTREAMS}/${d.value.id}`).catch((err) => {
// Ignore 404 errors as the resource might have been deleted
- if (axios.isAxiosError(err) && err.response?.status === 404) return;
+ // Ignore 400 errors as the upstream might still be referenced by routes/services
+ if (
+ axios.isAxiosError(err) &&
+ (err.response?.status === 404 || err.response?.status === 400)
+ ) {
+ return;
+ }
Review Comment:
`deleteAllUpstreams` now ignores *all* HTTP 400 responses on delete. Since 400 can indicate problems other than “still referenced”, this can silently mask real failures and leave upstreams behind unexpectedly. Consider narrowing the ignore condition to the specific APISIX error you expect for “referenced” upstreams (e.g., inspect response body/code), or use a more semantically appropriate status if APISIX provides one.
##########
e2e/tsconfig.tsbuildinfo:
##########
@@ -0,0 +1 @@
+{"root":["./pom/consumer_groups.ts","./pom/consumers.ts","./pom/credentials.ts","./pom/global_rules.ts","./pom/plugin_configs.ts","./pom/plugin_metadata.ts","./pom/protos.ts","./pom/routes.ts","./pom/secrets.ts","./pom/services.ts","./pom/ssls.ts","./pom/stream_routes.ts","./pom/type.ts","./pom/upstreams.ts","./tests/auth.spec.ts","./tests/consumer_groups.crud-all-fields.spec.ts","./tests/consumer_groups.crud-required-fields.spec.ts","./tests/consumer_groups.list.spec.ts","./tests/consumers.credentials.list.spec.ts","./tests/consumers.crud-all-fields.spec.ts","./tests/consumers.crud-required-fields.spec.ts","./tests/consumers.list.spec.ts","./tests/global_rules.crud-all-fields.spec.ts","./tests/global_rules.crud-required-fields.spec.ts","./tests/global_rules.list.spec.ts","./tests/hot-path.upstream-service-route.spec.ts","./tests/plugin_configs.crud-all-fields.spec.ts","./tests/plugin_configs.crud-required-fields.spec.ts","./tests/plugin_configs.list.spec.ts","./tests/plugin_metadat
a.crud-all-fields.spec.ts","./tests/plugin_metadata.crud-required-fields.spec.ts","./tests/plugin_metadata.list.spec.ts","./tests/protos.crud-all-fields.spec.ts","./tests/protos.crud-required-fields.spec.ts","./tests/protos.list.spec.ts","./tests/routes.clear-upstream-field.spec.ts","./tests/routes.crud-all-fields.spec.ts","./tests/routes.crud-required-fields.spec.ts","./tests/routes.list.spec.ts","./tests/secrets.crud-all-fields.spec.ts","./tests/secrets.crud-required-fields.spec.ts","./tests/secrets.list.spec.ts","./tests/services.crud-all-fields.spec.ts","./tests/services.crud-required-fields.spec.ts","./tests/services.empty.spec.ts","./tests/services.list.spec.ts","./tests/services.routes.crud.spec.ts","./tests/services.routes.list.spec.ts","./tests/services.stream_routes.crud.spec.ts","./tests/services.stream_routes.list.spec.ts","./tests/ssls.check-labels.spec.ts","./tests/ssls.crud-all-fields.spec.ts","./tests/ssls.crud-required-fields.spec.ts","./tests/ssls.list.spec.ts","./
tests/stream_routes.crud-all-fields.spec.ts","./tests/stream_routes.crud-required-fields.spec.ts","./tests/stream_routes.list.spec.ts","./tests/stream_routes.show-disabled-error.spec.ts","./tests/upstreams.crud-all-fields.spec.ts","./tests/upstreams.crud-required-fields.spec.ts","./tests/upstreams.list.spec.ts","./utils/common.ts","./utils/env.ts","./utils/pagination-test-helper.ts","./utils/req.ts","./utils/test.ts","./utils/ui/index.ts","./utils/ui/labels.ts","./utils/ui/routes.ts","./utils/ui/services.ts","./utils/ui/ssls.ts","./utils/ui/stream_routes.ts","./utils/ui/upstreams.ts","../src/types/global.d.ts"],"version":"5.8.3"}
Review Comment:
`e2e/tsconfig.tsbuildinfo` looks like a generated TypeScript build artifact and shouldn’t be committed. Please remove it from the repo and add an ignore rule (e.g., `**/*.tsbuildinfo`) so it won’t get reintroduced by local builds.
```suggestion
```
##########
e2e/utils/test.ts:
##########
@@ -24,50 +24,85 @@ import { env } from './env';
export type Test = typeof test;
export const test = baseTest.extend<object, { workerStorageState: string }>({
- storageState: ({ workerStorageState }, use) => use(workerStorageState),
+ storageState: ({ workerStorageState }, use) => {
+ return use(workerStorageState);
+ },
workerStorageState: [
async ({ browser }, use) => {
// Use parallelIndex as a unique identifier for each worker.
const id = test.info().parallelIndex;
- const fileName = path.resolve(
- test.info().project.outputDir,
- `.auth/${id}.json`
- );
+ const authDir = path.resolve(test.info().project.outputDir, '.auth');
+ const fileName = path.resolve(authDir, `${id}.json`);
const { adminKey } = await getAPISIXConf();
+ // Ensure .auth directory exists
+ await mkdir(authDir, { recursive: true });
+
// file exists and contains admin key, use it
- if (
- (await fileExists(fileName)) &&
- (await readFile(fileName)).toString().includes(adminKey)
- ) {
- return use(fileName);
+ if (await fileExists(fileName)) {
+ try {
+ const content = await readFile(fileName);
+ if (content.toString().includes(adminKey)) {
+ return use(fileName);
+ }
+ } catch {
+ // File exists but is unreadable, recreate it
+ }
}
- const page = await browser.newPage({ storageState: undefined });
+ let page;
+ try {
+ page = await browser.newPage({ storageState: undefined });
+
+ // have to use env here, because the baseURL is not available in worker
+ await page.goto(env.E2E_TARGET_URL, { waitUntil: 'load' });
+
+ // we need to authenticate
+ const settingsModal = page.getByRole('dialog', { name: 'Settings' });
+ await expect(settingsModal).toBeVisible({ timeout: 30000 });
+ // PasswordInput renders with a label, use getByLabel instead
+ const adminKeyInput = page.getByLabel('Admin Key');
+ await adminKeyInput.clear();
+ await adminKeyInput.fill(adminKey);
- // have to use env here, because the baseURL is not available in worker
- await page.goto(env.E2E_TARGET_URL);
+ const closeButton = page
+ .getByRole('dialog', { name: 'Settings' })
+ .getByRole('button');
+ await expect(closeButton).toBeVisible({ timeout: 10000 });
+ await closeButton.click();
- // we need to authenticate
- const settingsModal = page.getByRole('dialog', { name: 'Settings' });
- await expect(settingsModal).toBeVisible();
- // PasswordInput renders with a label, use getByLabel instead
- const adminKeyInput = page.getByLabel('Admin Key');
- await adminKeyInput.clear();
- await adminKeyInput.fill(adminKey);
- await page
- .getByRole('dialog', { name: 'Settings' })
- .getByRole('button')
- .click();
+ // Wait for auth to complete
+ await expect(settingsModal).toBeHidden({ timeout: 15000 });
+
+ // Wait for any post-auth navigation/loading to complete
+ await page.waitForLoadState('load');
+
+ await page.context().storageState({ path: fileName });
+
+ // Verify auth state file was created
+ if (!(await fileExists(fileName))) {
+ throw new Error(`Auth state file was not created at ${fileName}`);
+ }
+ } catch (error) {
+ console.error(`Failed to authenticate worker ${id}:`, error);
+ // Create an empty auth state file so Playwright doesn't fail
+ // Tests will retry auth on first page load
+ try {
+ await writeFile(fileName, JSON.stringify({ cookies: [], origins: [] }));
+ } catch (writeErr) {
+ console.error(`Failed to create fallback auth state: ${writeErr}`);
+ }
+ throw error;
+ } finally {
Review Comment:
The fallback-auth comment/behavior is inconsistent: after writing an empty storage state file, the fixture still `throw`s, so tests won’t proceed to “retry auth on first page load”. Either remove the fallback-file logic/comment, or don’t rethrow and instead continue with the empty storageState so tests can attempt interactive auth later.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Baluduvamsi2006 (via GitHub)" <gi...@apache.org>.
Baluduvamsi2006 closed pull request #3305: refactor(ui): introduce ResourceListPage and standardize resource list
URL: https://github.com/apache/apisix-dashboard/pull/3305
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Baluduvamsi2006 (via GitHub)" <gi...@apache.org>.
Baluduvamsi2006 commented on PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#issuecomment-3950913339
@Baoyuantop I have addressed all of the feedback and pushed the fixes! Could you please trigger the Copilot review again or review the changes?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#discussion_r2872374064
##########
src/routes/services/detail.$id/routes/index.tsx:
##########
@@ -55,4 +50,4 @@ export const Route = createFileRoute('/services/detail/$id/routes/')({
loaderDeps: ({ search }) => search,
loader: ({ deps }) =>
queryClient.ensureQueryData(getRouteListQueryOptions(deps)),
-});
+});
Review Comment:
The route loader prefetches `getRouteListQueryOptions(deps)` without the `service_id` filter, but the page renders `RouteList` with `defaultParams.filter.service_id`. This means the prefetched query key/data won’t match the suspense query and can briefly fetch/show the unfiltered list (and wastes the prefetch). Align the loader with the component by including `filter: { service_id: id }` (as done for service stream_routes).
##########
src/types/schema/pageSearch.ts:
##########
@@ -19,16 +19,14 @@ import { z } from 'zod';
export const pageSearchSchema = z
.object({
- page: z
- .union([z.string(), z.number()])
- .optional()
- .default(1)
- .transform((val) => (val ? Number(val) : 1)),
- page_size: z
- .union([z.string(), z.number()])
- .optional()
- .default(10)
- .transform((val) => (val ? Number(val) : 10)),
+ page: z.preprocess(
+ (val) => (val === undefined || val === null ? undefined : Number(val)),
+ z.number().optional().default(1)
+ ),
+ page_size: z.preprocess(
Review Comment:
`Number(val)` coercion will accept `0` (and turns an empty string into `0`), so `page=0` can now pass validation and yield `current: 0` in AntD pagination. Consider coercing only non-empty values and adding `int().min(1)` (and similarly for `page_size`) to preserve prior behavior where falsy/0 defaulted to 1/10.
##########
e2e/server/apisix_conf.yml:
##########
@@ -1,42 +1,22 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You 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.
-#
-
apisix:
- node_listen: 9080 # APISIX listening port
+ node_listen: 9080
enable_ipv6: false
Review Comment:
The ASF license header was removed from this config file, but other files under `e2e/server/` (e.g. `docker-compose.yml`) still include it. To stay consistent with repository licensing conventions, please restore the header here as well.
##########
e2e/utils/test.ts:
##########
@@ -43,31 +44,45 @@ export const test = baseTest.extend<object, { workerStorageState: string }>({
return use(fileName);
}
- const page = await browser.newPage({ storageState: undefined });
+ try {
+ const page = await browser.newPage({ storageState: undefined });
+
+ // have to use env here, because the baseURL is not available in worker
+ await page.goto(env.E2E_TARGET_URL, { waitUntil: 'load' });
Review Comment:
`page` is created inside the `try`, but in the `catch` branch it won’t be closed, which can leak pages/contexts and make subsequent tests flaky when auth fails. Consider declaring `let page` outside and closing it in a `finally` (or `await page?.close()` in the catch) before rethrowing.
##########
playwright.config.ts:
##########
@@ -24,10 +24,10 @@ import { env } from './e2e/utils/env';
export default defineConfig({
testDir: './e2e/tests',
outputDir: './test-results',
- fullyParallel: true,
+ fullyParallel: false,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
- workers: process.env.CI ? 1 : undefined,
+ workers: 1,
Review Comment:
`fullyParallel: false` and `workers: 1` are now forced for all runs (including local), which can significantly slow down E2E and conflicts with the stated goal of improved parallel execution. If the intent is CI stability only, consider gating these behind `process.env.CI` (or document why local parallelism is intentionally disabled).
##########
e2e/tests/stream_routes.show-disabled-error.spec.ts:
##########
@@ -51,8 +51,7 @@ type APISIXConf = {
};
const getE2EServerDir = () => {
- const currentDir = new URL('.', import.meta.url).pathname;
- return path.join(currentDir, '../server');
+ return path.join(process.cwd(), 'e2e/server');
};
Review Comment:
Using `process.cwd()` makes this path dependent on how Playwright is invoked (it can differ in some CI/devcontainer setups). For consistency with the cross-platform fix used in `e2e/utils/common.ts` (fileURLToPath(import.meta.url)), consider deriving the directory from `import.meta.url` instead of the current working directory.
##########
src/components/page/ResourceListPage.tsx:
##########
@@ -0,0 +1,128 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 type { ProColumns } from '@ant-design/pro-components';
+import { ProTable } from '@ant-design/pro-components';
+import type { TablePaginationConfig } from 'antd';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { AntdConfigProvider } from '@/config/antdConfigProvider';
+
+import PageHeader from './PageHeader';
+import type { ToAddPageBtnProps } from './ToAddPageBtn';
+import { ToAddPageBtn } from './ToAddPageBtn';
+
+interface ResourceListPageProps<T> {
+ titleKey?: string;
+ columns: ProColumns<T>[];
+ queryData: {
+ data?: { list: T[]; total: number } | undefined;
+ isLoading: boolean;
+ pagination: TablePaginationConfig | false;
+ refetch?: () => void;
+ };
+ rowKey: string | ((record: T) => string);
+ addPageTo?: ToAddPageBtnProps['to'];
+ resourceNameKey?: string;
+ emptyText?: React.ReactNode;
+ pageSizeOptions?: number[] | string[];
+ showTotal?: (total: number, range: [number, number]) => React.ReactNode;
+}
+
+function isRecord(val: unknown): val is Record<string, unknown> {
+ return val !== null && typeof val === 'object' && !Array.isArray(val);
+}
+
+const ResourceListPage = <T extends Record<string, unknown>>(
+ props: ResourceListPageProps<T>,
+) => {
+ const {
+ titleKey,
+ columns,
+ queryData,
+ rowKey,
+ addPageTo,
+ resourceNameKey,
+ emptyText,
+ pageSizeOptions,
+ showTotal: customShowTotal,
+ } = props;
+ const { t } = useTranslation();
+ const { data, isLoading, pagination } = queryData;
+
+ const dataSource = useMemo(() => data?.list ?? [], [data]);
+ const total =
+ (pagination !== false ? pagination?.total : undefined) ?? data?.total ?? 0;
+
+ const paginationConfig = useMemo(() => {
+ if (pagination === false) return false;
+
+ return {
+ current: pagination?.current ?? 1,
+ pageSize: pagination?.pageSize ?? 10,
+ total,
+ showSizeChanger: true,
+ pageSizeOptions: pageSizeOptions ?? [10, 20, 50, 100],
+ hideOnSinglePage: false,
+ onChange: pagination?.onChange,
+ ...(customShowTotal ? { showTotal: customShowTotal } : {}),
+ };
+ }, [pagination, total, pageSizeOptions, customShowTotal]);
+
+ const resolvedRowKey = useMemo(
+ () =>
+ typeof rowKey === 'function'
+ ? rowKey
+ : (record: T) => {
+ // APISIX list items wrap data in a `value` property
+ const raw = record['value'];
+ const value = isRecord(raw) ? raw : undefined;
+ return String(value?.[rowKey] ?? record[rowKey] ?? '');
+ },
+ [rowKey],
+ );
+
+ return (
+ <AntdConfigProvider>
+ {titleKey && <PageHeader title={t(titleKey, titleKey)} />}
+ <ProTable<T>
+ columns={columns}
+ dataSource={dataSource}
+ rowKey={resolvedRowKey}
+ loading={isLoading}
+ search={false}
+ options={false}
+ pagination={paginationConfig}
+ cardProps={{ bodyStyle: { padding: 0 } }}
+ locale={emptyText ? { emptyText } : undefined}
+ toolBarRender={() => [
+ addPageTo && resourceNameKey && (
+ <ToAddPageBtn
+ key="create"
+ to={addPageTo}
Review Comment:
This uses `toolBarRender` to render the “Add” action, but existing list pages used `toolbar.menu` with `type: 'inline'` (e.g., credentials list still does). If the goal is 1:1 UI behavior/standardization, consider using the same `toolbar.menu` approach here (or refactor the remaining tables) so the Add control lands in the same place and keeps consistent styling.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#discussion_r2897105076
##########
e2e/tests/services.routes.list.spec.ts:
##########
@@ -34,208 +35,217 @@ const routes: APISIXType['Route'][] = [
name: randomId('route1'),
uri: '/api/v1/test1',
methods: ['GET'],
+ labels: { test: serviceName },
},
{
name: randomId('route2'),
uri: '/api/v1/test2',
methods: ['POST'],
+ labels: { test: serviceName },
},
{
name: randomId('route3'),
uri: '/api/v1/test3',
methods: ['PUT'],
+ labels: { test: serviceName },
},
];
-// Route that uses upstream directly instead of service_id
+const upstreamRouteName = randomId('upstream-route');
const upstreamRoute: APISIXType['Route'] = {
- name: randomId('upstream-route'),
+ name: upstreamRouteName,
uri: '/api/v1/upstream-test',
methods: ['GET'],
upstream: {
nodes: [{ host: 'example.com', port: 80, weight: 100 }],
},
+ labels: { test: upstreamRouteName },
};
-// Route that belongs to another service
+const anotherServiceRouteName = randomId('another-service-route');
const anotherServiceRoute: APISIXType['Route'] = {
- name: randomId('another-service-route'),
+ name: anotherServiceRouteName,
uri: '/api/v1/another-test',
methods: ['GET'],
+ labels: { test: anotherServiceName },
};
let testServiceId: string;
let anotherServiceId: string;
const createdRoutes: string[] = [];
-test.beforeAll(async () => {
- await deleteAllRoutes(e2eReq);
- await deleteAllServices(e2eReq);
+let upstreamRouteId: string;
+let anotherServiceRouteId: string;
- // Create a test service for testing service routes
+test.beforeAll(async () => {
const serviceResponse = await postServiceReq(e2eReq, {
name: serviceName,
desc: 'Test service for route listing',
+ labels: { test: serviceName },
});
testServiceId = serviceResponse.data.value.id;
- // Create another service
const anotherServiceResponse = await postServiceReq(e2eReq, {
name: anotherServiceName,
desc: 'Another test service for route isolation testing',
+ labels: { test: anotherServiceName },
});
anotherServiceId = anotherServiceResponse.data.value.id;
- // Create test routes under the service
for (const route of routes) {
const routeResponse = await postRouteReq(e2eReq, {
- ...route,
+ ...(route as Record<string, unknown>),
service_id: testServiceId,
});
+ if (!routeResponse.data?.value) {
+ throw new Error(`Failed to create route: ${JSON.stringify(routeResponse.data)}`);
+ }
createdRoutes.push(routeResponse.data.value.id);
}
- // Create a route that uses upstream directly instead of service_id
- await postRouteReq(e2eReq, upstreamRoute);
- // Create a route under another service
- await postRouteReq(e2eReq, {
- ...anotherServiceRoute,
+ const upstreamRouteResponse = await postRouteReq(e2eReq, upstreamRoute as unknown as Parameters<typeof postRouteReq>[1]);
+ if (!upstreamRouteResponse.data?.value) {
Review Comment:
This test uses several broad type casts (`route as Record<string, unknown>`, `upstreamRoute as unknown as Parameters<typeof postRouteReq>[1]`) when calling `postRouteReq`, which defeats type-checking for the request payload and can hide breaking API changes. Prefer declaring the fixtures using the actual `postRouteReq` payload type (e.g. `RoutePostType` / `Parameters<typeof postRouteReq>[1]`) and constructing the objects without `unknown`/`Record` casts.
##########
src/types/schema/pageSearch.ts:
##########
@@ -19,16 +19,22 @@ import { z } from 'zod';
export const pageSearchSchema = z
.object({
- page: z
- .union([z.string(), z.number()])
- .optional()
- .default(1)
- .transform((val) => (val ? Number(val) : 1)),
- page_size: z
- .union([z.string(), z.number()])
- .optional()
- .default(10)
- .transform((val) => (val ? Number(val) : 10)),
+ page: z.preprocess(
+ (val) => {
+ if (val === undefined || val === null || val === '') return undefined;
+ const num = Number(val);
+ return Number.isNaN(num) || num <= 0 ? undefined : num;
+ },
+ z.number().int().min(1).optional().default(1)
+ ),
+ page_size: z.preprocess(
+ (val) => {
+ if (val === undefined || val === null || val === '') return undefined;
+ const num = Number(val);
+ return Number.isNaN(num) || num <= 0 ? undefined : num;
+ },
+ z.number().int().min(1).optional().default(10)
+ ),
Review Comment:
`page` / `page_size` preprocessing currently allows non-integer numeric inputs (e.g. `page=1.5`) through the preprocess step, which then fails `z.number().int()` and can cause `validateSearch` / `pageSearchSchema.parse(...)` to throw for malformed URLs. Consider also treating non-integer values as invalid in the preprocess (e.g. return `undefined` when `!Number.isInteger(num)`) so the schema reliably falls back to defaults instead of erroring.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Baluduvamsi2006 (via GitHub)" <gi...@apache.org>.
Baluduvamsi2006 closed pull request #3305: refactor(ui): introduce ResourceListPage and standardize resource list
URL: https://github.com/apache/apisix-dashboard/pull/3305
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] refactor(ui): introduce ResourceListPage and standardize resource list [apisix-dashboard]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3305:
URL: https://github.com/apache/apisix-dashboard/pull/3305#discussion_r2896904114
##########
e2e/utils/req.ts:
##########
@@ -27,30 +27,61 @@ export const getPlaywrightRequestAdapter = (
ctx: APIRequestContext
): AxiosAdapter => {
return async (config) => {
- const { url, data, baseURL } = config;
+ const { url, data, baseURL, method } = config;
if (typeof url === 'undefined') {
throw new Error('Need to provide a url');
}
type Payload = Parameters<APIRequestContext['fetch']>[1];
const payload: Payload = {
headers: config.headers,
- method: config.method,
- failOnStatusCode: true,
+ method,
+ failOnStatusCode: false,
data,
};
const urlWithBase = `${baseURL}${url}`;
const res = await ctx.fetch(urlWithBase, payload);
+ const status = res.status();
- try {
+ // Idempotent DELETE: Treat 404 as 200 OK
+ if (method?.toLowerCase() === 'delete' && status === 404) {
+ console.warn(`[e2eReq] Ignored 404 on DELETE for ${urlWithBase}, treating as 200 OK.`);
return {
+ data: {},
+ status: 200,
+ statusText: 'OK',
+ headers: {},
+ config,
+ };
+ }
+
+ try {
+ let responseData = {};
+ try {
+ responseData = await res.json();
+ } catch {
+ // ignore JSON parse errors on empty or text responses
+ }
+ const response = {
...res,
- data: await res.json(),
+ data: responseData,
config,
- status: res.status(),
+ status,
statusText: res.statusText(),
headers: res.headers(),
};
+
+ if (config.validateStatus && !config.validateStatus(status)) {
+ throw new AxiosError(
+ `Request failed with status code ${status}`,
+ AxiosError.ERR_BAD_REQUEST,
+ config as unknown as InternalAxiosRequestConfig,
+ undefined,
+ response as unknown as AxiosResponse
+ );
Review Comment:
In the adapter's validateStatus failure path, the thrown AxiosError always uses `AxiosError.ERR_BAD_REQUEST`. Axios distinguishes 4xx vs 5xx (`ERR_BAD_REQUEST` for 4xx, `ERR_BAD_RESPONSE` for 5xx). Using the wrong code can break assertions/logic that relies on `error.code`. Consider selecting the error code based on `status` to match Axios behavior more closely.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org