feat: dedicated route to get intermediates count

This fixes a weird issue where the list images method needed to handle `None` for its `limit` and `offset` arguments, in order to get a count of all intermediates.
This commit is contained in:
psychedelicious 2023-10-17 18:28:36 +11:00
parent 677918df61
commit 9195c8c957
8 changed files with 106 additions and 45 deletions

View File

@ -87,7 +87,7 @@ async def delete_image(
pass
@images_router.post("/clear-intermediates", operation_id="clear_intermediates")
@images_router.delete("/intermediates", operation_id="clear_intermediates")
async def clear_intermediates() -> int:
"""Clears all intermediates"""
@ -99,6 +99,17 @@ async def clear_intermediates() -> int:
pass
@images_router.get("/intermediates", operation_id="get_intermediates_count")
async def get_intermediates_count() -> int:
"""Gets the count of intermediate images"""
try:
return ApiDependencies.invoker.services.images.get_intermediates_count()
except Exception:
raise HTTPException(status_code=500, detail="Failed to get intermediates")
pass
@images_router.patch(
"/i/{image_name}",
operation_id="update_image",

View File

@ -61,6 +61,11 @@ class ImageRecordStorageBase(ABC):
"""Deletes all intermediate image records, returning a list of deleted image names."""
pass
@abstractmethod
def get_intermediates_count(self) -> int:
"""Gets a count of all intermediate images."""
pass
@abstractmethod
def save(
self,

View File

@ -297,11 +297,8 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
images_query += query_conditions + query_pagination + ";"
# Add all the parameters
images_params = query_params.copy()
if limit is not None:
images_params.append(limit)
if offset is not None:
images_params.append(offset)
# Add the pagination parameters
images_params.extend([limit, offset])
# Build the list of images, deserializing each row
self._cursor.execute(images_query, images_params)
@ -357,6 +354,24 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
finally:
self._lock.release()
def get_intermediates_count(self) -> int:
try:
self._lock.acquire()
self._cursor.execute(
"""--sql
SELECT COUNT(*) FROM images
WHERE is_intermediate = TRUE;
"""
)
count = cast(int, self._cursor.fetchone()[0])
self._conn.commit()
return count
except sqlite3.Error as e:
self._conn.rollback()
raise ImageRecordDeleteException from e
finally:
self._lock.release()
def delete_intermediates(self) -> list[str]:
try:
self._lock.acquire()

View File

@ -123,6 +123,11 @@ class ImageServiceABC(ABC):
"""Deletes all intermediate images."""
pass
@abstractmethod
def get_intermediates_count(self) -> int:
"""Gets the number of intermediate images."""
pass
@abstractmethod
def delete_images_on_board(self, board_id: str):
"""Deletes all images on a board."""

View File

@ -284,3 +284,10 @@ class ImageService(ImageServiceABC):
except Exception as e:
self.__invoker.services.logger.error("Problem deleting image records and files")
raise e
def get_intermediates_count(self) -> int:
try:
return self.__invoker.services.image_records.get_intermediates_count()
except Exception as e:
self.__invoker.services.logger.error("Problem getting intermediates count")
raise e

View File

@ -1,7 +1,7 @@
import { Heading, Text } from '@chakra-ui/react';
import { useAppDispatch } from 'app/store/storeHooks';
import { controlAdaptersReset } from 'features/controlAdapters/store/controlAdaptersSlice';
import { useCallback, useEffect } from 'react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useGetQueueStatusQuery } from 'services/api/endpoints/queue';
import IAIButton from '../../../../common/components/IAIButton';
@ -17,8 +17,12 @@ export default function SettingsClearIntermediates() {
const { t } = useTranslation();
const dispatch = useAppDispatch();
const { data: intermediatesCount, refetch: updateIntermediatesCount } =
useGetIntermediatesCountQuery();
const { data: intermediatesCount } = useGetIntermediatesCountQuery(
undefined,
{
refetchOnMountOrArgChange: true,
}
);
const [clearIntermediates, { isLoading: isLoadingClearIntermediates }] =
useClearIntermediatesMutation();
@ -55,11 +59,6 @@ export default function SettingsClearIntermediates() {
});
}, [t, clearIntermediates, dispatch, hasPendingItems]);
useEffect(() => {
// update the count on mount
updateIntermediatesCount();
}, [updateIntermediatesCount]);
return (
<StyledFlex>
<Heading size="sm">{t('settings.clearIntermediates')}</Heading>

View File

@ -100,14 +100,12 @@ export const imagesApi = api.injectEndpoints({
keepUnusedDataFor: 86400,
}),
getIntermediatesCount: build.query<number, void>({
query: () => ({ url: getListImagesUrl({ is_intermediate: true }) }),
query: () => ({ url: 'images/intermediates' }),
providesTags: ['IntermediatesCount'],
transformResponse: (response: OffsetPaginatedResults_ImageDTO_) => {
// TODO: This is storing a primitive value in the cache. `immer` cannot track state changes, so
// attempts to use manual cache updates on this value will fail. This should be changed into an
// object.
return response.total;
},
}),
clearIntermediates: build.mutation<number, void>({
query: () => ({ url: `images/intermediates`, method: 'DELETE' }),
invalidatesTags: ['IntermediatesCount'],
}),
getImageDTO: build.query<ImageDTO, string>({
query: (image_name) => ({ url: `images/i/${image_name}` }),
@ -185,10 +183,6 @@ export const imagesApi = api.injectEndpoints({
],
keepUnusedDataFor: 86400, // 24 hours
}),
clearIntermediates: build.mutation<number, void>({
query: () => ({ url: `images/clear-intermediates`, method: 'POST' }),
invalidatesTags: ['IntermediatesCount'],
}),
deleteImage: build.mutation<void, ImageDTO>({
query: ({ image_name }) => ({
url: `images/i/${image_name}`,

File diff suppressed because one or more lines are too long