Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: enhance s3 logs retention handling (#9371)

Shaheer Kochai718360a966e0
diff --git a/frontend/src/api/settings/setRetentionV2.ts b/frontend/src/api/settings/setRetentionV2.ts
index bd7e56d8e5..a123d08d3e 100644
--- a/frontend/src/api/settings/setRetentionV2.ts
+++ b/frontend/src/api/settings/setRetentionV2.ts
@@ -8,7 +8,7 @@ const setRetentionV2 = async ({
type,
defaultTTLDays,
coldStorageVolume,
- coldStorageDuration,
+ coldStorageDurationDays,
ttlConditions,
}: PropsV2): Promise<SuccessResponseV2<PayloadPropsV2>> => {
try {
@@ -16,7 +16,7 @@ const setRetentionV2 = async ({
type,
defaultTTLDays,
coldStorageVolume,
- coldStorageDuration,
+ coldStorageDurationDays,
ttlConditions,
});
diff --git a/frontend/src/container/GeneralSettings/GeneralSettings.tsx b/frontend/src/container/GeneralSettings/GeneralSettings.tsx
index fc8fc156a3..71e62ddfbf 100644
--- a/frontend/src/container/GeneralSettings/GeneralSettings.tsx
+++ b/frontend/src/container/GeneralSettings/GeneralSettings.tsx
@@ -137,8 +137,9 @@ function GeneralSettings({
if (logsCurrentTTLValues) {
setLogsTotalRetentionPeriod(logsCurrentTTLValues.default_ttl_days * 24);
setLogsS3RetentionPeriod(
- logsCurrentTTLValues.logs_move_ttl_duration_hrs
- ? logsCurrentTTLValues.logs_move_ttl_duration_hrs
+ logsCurrentTTLValues.cold_storage_ttl_days &&
+ logsCurrentTTLValues.cold_storage_ttl_days > 0
+ ? logsCurrentTTLValues.cold_storage_ttl_days * 24
: null,
);
}
@@ -198,7 +199,12 @@ function GeneralSettings({
);
const s3Enabled = useMemo(
- () => !!find(availableDisks, (disks: IDiskType) => disks?.type === 's3'),
+ () =>
+ !!find(
+ availableDisks,
+ (disks: IDiskType) =>
+ disks?.type === 's3' || disks?.type === 'ObjectStorage',
+ ),
[availableDisks],
);
@@ -289,8 +295,9 @@ function GeneralSettings({
isTracesSaveDisabled = true;
if (
- logsCurrentTTLValues.logs_ttl_duration_hrs === logsTotalRetentionPeriod &&
- logsCurrentTTLValues.logs_move_ttl_duration_hrs === logsS3RetentionPeriod
+ logsCurrentTTLValues.default_ttl_days * 24 === logsTotalRetentionPeriod &&
+ logsCurrentTTLValues.cold_storage_ttl_days &&
+ logsCurrentTTLValues.cold_storage_ttl_days * 24 === logsS3RetentionPeriod
)
isLogsSaveDisabled = true;
@@ -301,8 +308,8 @@ function GeneralSettings({
errorText,
];
}, [
- logsCurrentTTLValues.logs_move_ttl_duration_hrs,
- logsCurrentTTLValues.logs_ttl_duration_hrs,
+ logsCurrentTTLValues.cold_storage_ttl_days,
+ logsCurrentTTLValues.default_ttl_days,
logsS3RetentionPeriod,
logsTotalRetentionPeriod,
metricsCurrentTTLValues.metrics_move_ttl_duration_hrs,
@@ -348,11 +355,17 @@ function GeneralSettings({
try {
if (type === 'logs') {
+ // Only send S3 values if user has specified a duration
+ const s3RetentionDays =
+ apiCallS3Retention && apiCallS3Retention > 0
+ ? apiCallS3Retention / 24
+ : 0;
+
await setRetentionApiV2({
type,
defaultTTLDays: apiCallTotalRetention ? apiCallTotalRetention / 24 : -1, // convert Hours to days
- coldStorageVolume: '',
- coldStorageDuration: 0,
+ coldStorageVolume: s3RetentionDays > 0 ? 's3' : '',
+ coldStorageDurationDays: s3RetentionDays,
ttlConditions: [],
});
} else {
@@ -406,8 +419,9 @@ function GeneralSettings({
// Updates the currentTTL Values in order to avoid pushing the same values.
setLogsCurrentTTLValues((prev) => ({
...prev,
- logs_ttl_duration_hrs: logsTotalRetentionPeriod || -1,
- logs_move_ttl_duration_hrs: logsS3RetentionPeriod || -1,
+ cold_storage_ttl_days: logsS3RetentionPeriod
+ ? logsS3RetentionPeriod / 24
+ : -1,
default_ttl_days: logsTotalRetentionPeriod
? logsTotalRetentionPeriod / 24 // convert Hours to days
: -1,
@@ -524,6 +538,7 @@ function GeneralSettings({
value: logsS3RetentionPeriod,
setValue: setLogsS3RetentionPeriod,
hide: !s3Enabled,
+ isS3Field: true,
},
],
save: {
@@ -577,6 +592,7 @@ function GeneralSettings({
retentionValue={retentionField.value}
setRetentionValue={retentionField.setValue}
hide={!!retentionField.hide}
+ isS3Field={'isS3Field' in retentionField && retentionField.isS3Field}
/>
))}
diff --git a/frontend/src/container/GeneralSettings/Retention.tsx b/frontend/src/container/GeneralSettings/Retention.tsx
index 9c05fbec3a..30e24c42bf 100644
--- a/frontend/src/container/GeneralSettings/Retention.tsx
+++ b/frontend/src/container/GeneralSettings/Retention.tsx
@@ -6,6 +6,7 @@ import {
Dispatch,
SetStateAction,
useEffect,
+ useMemo,
useRef,
useState,
} from 'react';
@@ -32,11 +33,31 @@ function Retention({
setRetentionValue,
text,
hide,
+ isS3Field = false,
}: RetentionProps): JSX.Element | null {
+ // Filter available units based on type and field
+ const availableUnits = useMemo(
+ () =>
+ TimeUnits.filter((option) => {
+ if (type === 'logs') {
+ // For S3 cold storage fields: only allow Days
+ if (isS3Field) {
+ return option.value === TimeUnitsValues.day;
+ }
+ // For total retention: allow Days and Months (not Hours)
+ return option.value !== TimeUnitsValues.hr;
+ }
+ return true;
+ }),
+ [type, isS3Field],
+ );
+
+ // Convert the hours value using only the available units
const {
value: initialValue,
timeUnitValue: initialTimeUnitValue,
- } = convertHoursValueToRelevantUnit(Number(retentionValue));
+ } = convertHoursValueToRelevantUnit(Number(retentionValue), availableUnits);
+
const [selectedTimeUnit, setSelectTimeUnit] = useState(initialTimeUnitValue);
const [selectedValue, setSelectedValue] = useState<number | null>(
initialValue,
@@ -53,29 +74,27 @@ function Retention({
if (!interacted.current) setSelectTimeUnit(initialTimeUnitValue);
}, [initialTimeUnitValue]);
- const menuItems = TimeUnits.filter((option) =>
- type === 'logs' ? option.value !== TimeUnitsValues.hr : true,
- ).map((option) => (
+ const menuItems = availableUnits.map((option) => (
<Option key={option.value} value={option.value}>
{option.key}
</Option>
));
const currentSelectedOption = (option: SettingPeriod): void => {
- const selectedValue = find(TimeUnits, (e) => e.value === option)?.value;
+ const selectedValue = find(availableUnits, (e) => e.value === option)?.value;
if (selectedValue) setSelectTimeUnit(selectedValue);
};
useEffect(() => {
const inverseMultiplier = find(
- TimeUnits,
+ availableUnits,
(timeUnit) => timeUnit.value === selectedTimeUnit,
)?.multiplier;
if (!selectedValue) setRetentionValue(null);
if (selectedValue && inverseMultiplier) {
setRetentionValue(selectedValue * (1 / inverseMultiplier));
}
- }, [selectedTimeUnit, selectedValue, setRetentionValue]);
+ }, [selectedTimeUnit, selectedValue, setRetentionValue, availableUnits]);
const onChangeHandler = (
e: ChangeEvent<HTMLInputElement>,
@@ -134,6 +153,10 @@ interface RetentionProps {
text: string;
setRetentionValue: Dispatch<SetStateAction<number | null>>;
hide: boolean;
+ isS3Field?: boolean;
}
+Retention.defaultProps = {
+ isS3Field: false,
+};
export default Retention;
diff --git a/frontend/src/container/GeneralSettings/__tests__/GeneralSettings.test.tsx b/frontend/src/container/GeneralSettings/__tests__/GeneralSettings.test.tsx
new file mode 100644
index 0000000000..81f5d5fd2c
--- /dev/null
+++ b/frontend/src/container/GeneralSettings/__tests__/GeneralSettings.test.tsx
@@ -0,0 +1,332 @@
+import setRetentionApiV2 from 'api/settings/setRetentionV2';
+import {
+ fireEvent,
+ render,
+ screen,
+ userEvent,
+ waitFor,
+} from 'tests/test-utils';
+import { IDiskType } from 'types/api/disks/getDisks';
+import {
+ PayloadPropsLogs,
+ PayloadPropsMetrics,
+ PayloadPropsTraces,
+} from 'types/api/settings/getRetention';
+
+import GeneralSettings from '../GeneralSettings';
+
+// Mock dependencies
+jest.mock('api/settings/setRetentionV2');
+
+const mockNotifications = {
+ error: jest.fn(),
+ success: jest.fn(),
+};
+
+jest.mock('hooks/useNotifications', () => ({
+ useNotifications: (): { notifications: typeof mockNotifications } => ({
+ notifications: mockNotifications,
+ }),
+}));
+
+jest.mock('hooks/useComponentPermission', () => ({
+ __esModule: true,
+ default: jest.fn(() => [true]),
+}));
+
+jest.mock('hooks/useGetTenantLicense', () => ({
+ useGetTenantLicense: (): { isCloudUser: boolean } => ({
+ isCloudUser: false,
+ }),
+}));
+
+jest.mock('container/GeneralSettingsCloud', () => ({
+ __esModule: true,
+ default: (): null => null,
+}));
+
+// Mock data
+const mockMetricsRetention: PayloadPropsMetrics = {
+ metrics_ttl_duration_hrs: 168,
+ metrics_move_ttl_duration_hrs: -1,
+ status: '',
+};
+
+const mockTracesRetention: PayloadPropsTraces = {
+ traces_ttl_duration_hrs: 168,
+ traces_move_ttl_duration_hrs: -1,
+ status: '',
+};
+
+const mockLogsRetentionWithS3: PayloadPropsLogs = {
+ version: 'v2',
+ default_ttl_days: 30,
+ cold_storage_ttl_days: 24,
+ status: '',
+};
+
+const mockLogsRetentionWithoutS3: PayloadPropsLogs = {
+ version: 'v2',
+ default_ttl_days: 30,
+ cold_storage_ttl_days: -1,
+ status: '',
+};
+
+const mockDisksWithS3: IDiskType[] = [
+ {
+ name: 'default',
+ type: 's3',
+ },
+];
+
+const mockDisksWithObjectStorage: IDiskType[] = [
+ {
+ name: 'default',
+ type: 'ObjectStorage',
+ },
+];
+
+const mockDisksWithoutS3: IDiskType[] = [
+ {
+ name: 'default',
+ type: 'local',
+ },
+];
+
+describe('GeneralSettings - S3 Logs Retention', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ (setRetentionApiV2 as jest.Mock).mockResolvedValue({
+ httpStatusCode: 200,
+ data: { message: 'success' },
+ });
+ });
+
+ describe('Test 1: S3 Enabled - Only Days in Dropdown', () => {
+ it('should show only Days option for S3 retention and send correct API payload', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ render(
+ <GeneralSettings
+ metricsTtlValuesPayload={mockMetricsRetention}
+ tracesTtlValuesPayload={mockTracesRetention}
+ logsTtlValuesPayload={mockLogsRetentionWithS3}
+ getAvailableDiskPayload={mockDisksWithS3}
+ metricsTtlValuesRefetch={jest.fn()}
+ tracesTtlValuesRefetch={jest.fn()}
+ logsTtlValuesRefetch={jest.fn()}
+ />,
+ );
+
+ // Find the Logs card
+ const logsCard = screen.getByText('Logs').closest('.ant-card');
+ expect(logsCard).toBeInTheDocument();
+
+ // Find all inputs in the Logs card - there should be 2 (total retention + S3)
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ const inputs = logsCard?.querySelectorAll('input[type="text"]');
+ expect(inputs).toHaveLength(2);
+
+ // The second input is the S3 retention field
+ const s3Input = inputs?.[1] as HTMLInputElement;
+
+ // Find the S3 dropdown (next sibling of the S3 input)
+ const s3Dropdown = s3Input?.nextElementSibling?.querySelector(
+ '.ant-select-selector',
+ ) as HTMLElement;
+ expect(s3Dropdown).toBeInTheDocument();
+
+ // Click the S3 dropdown to open it
+ fireEvent.mouseDown(s3Dropdown);
+
+ // Wait for dropdown options to appear and verify only "Days" is available
+ await waitFor(() => {
+ // eslint-disable-next-line sonarjs/no-duplicate-string
+ const dropdownOptions = document.querySelectorAll('.ant-select-item');
+ expect(dropdownOptions).toHaveLength(1);
+ expect(dropdownOptions[0]).toHaveTextContent('Days');
+ });
+
+ // Close dropdown
+ fireEvent.click(document.body);
+
+ // Change S3 retention value to 5 days
+ await user.clear(s3Input);
+ await user.type(s3Input, '5');
+
+ // Find the save button in the Logs card
+ const buttons = logsCard?.querySelectorAll('button[type="button"]');
+ // The primary button should be the save button
+ const saveButton = Array.from(buttons || []).find((btn) =>
+ btn.className.includes('ant-btn-primary'),
+ ) as HTMLButtonElement;
+
+ expect(saveButton).toBeInTheDocument();
+
+ // Wait for button to be enabled (it should enable after value changes)
+ await waitFor(() => {
+ expect(saveButton).not.toBeDisabled();
+ });
+
+ fireEvent.click(saveButton);
+
+ // Wait for modal to appear
+ const modal = await screen.findByRole('dialog');
+ expect(modal).toBeInTheDocument();
+
+ // Click OK button
+ const okButton = await screen.findByRole('button', { name: /ok/i });
+ fireEvent.click(okButton);
+
+ // Verify API was called with correct payload
+ await waitFor(() => {
+ expect(setRetentionApiV2).toHaveBeenCalledWith({
+ type: 'logs',
+ defaultTTLDays: 30,
+ coldStorageVolume: 's3',
+ coldStorageDurationDays: 5,
+ ttlConditions: [],
+ });
+ });
+ });
+
+ it('should recognize ObjectStorage disk type as S3 enabled', async () => {
+ render(
+ <GeneralSettings
+ metricsTtlValuesPayload={mockMetricsRetention}
+ tracesTtlValuesPayload={mockTracesRetention}
+ logsTtlValuesPayload={mockLogsRetentionWithS3}
+ getAvailableDiskPayload={mockDisksWithObjectStorage}
+ metricsTtlValuesRefetch={jest.fn()}
+ tracesTtlValuesRefetch={jest.fn()}
+ logsTtlValuesRefetch={jest.fn()}
+ />,
+ );
+
+ // Verify S3 field is visible
+ const logsCard = screen.getByText('Logs').closest('.ant-card');
+ const inputs = logsCard?.querySelectorAll('input[type="text"]');
+ expect(inputs).toHaveLength(2); // Total + S3
+ });
+ });
+
+ describe('Test 2: S3 Disabled - Field Hidden', () => {
+ it('should hide S3 retention field and send empty S3 values to API', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ render(
+ <GeneralSettings
+ metricsTtlValuesPayload={mockMetricsRetention}
+ tracesTtlValuesPayload={mockTracesRetention}
+ logsTtlValuesPayload={mockLogsRetentionWithoutS3}
+ getAvailableDiskPayload={mockDisksWithoutS3}
+ metricsTtlValuesRefetch={jest.fn()}
+ tracesTtlValuesRefetch={jest.fn()}
+ logsTtlValuesRefetch={jest.fn()}
+ />,
+ );
+
+ // Find the Logs card
+ const logsCard = screen.getByText('Logs').closest('.ant-card');
+ expect(logsCard).toBeInTheDocument();
+
+ // Only 1 input should be visible (total retention, no S3)
+ const inputs = logsCard?.querySelectorAll('input[type="text"]');
+ expect(inputs).toHaveLength(1);
+
+ // Change total retention value
+ const totalInput = inputs?.[0] as HTMLInputElement;
+
+ // First, change the dropdown to Days (it defaults to Months)
+ const totalDropdown = totalInput?.nextElementSibling?.querySelector(
+ '.ant-select-selector',
+ ) as HTMLElement;
+ await user.click(totalDropdown);
+
+ // Wait for dropdown options to appear
+ await waitFor(() => {
+ const options = document.querySelectorAll('.ant-select-item');
+ expect(options.length).toBeGreaterThan(0);
+ });
+
+ // Find and click the Days option
+ const options = document.querySelectorAll('.ant-select-item');
+ const daysOption = Array.from(options).find((opt) =>
+ opt.textContent?.includes('Days'),
+ );
+ expect(daysOption).toBeInTheDocument();
+ await user.click(daysOption as HTMLElement);
+
+ // Now change the value
+ await user.clear(totalInput);
+ await user.type(totalInput, '60');
+
+ // Find the save button
+ const buttons = logsCard?.querySelectorAll('button[type="button"]');
+ const saveButton = Array.from(buttons || []).find((btn) =>
+ btn.className.includes('ant-btn-primary'),
+ ) as HTMLButtonElement;
+
+ expect(saveButton).toBeInTheDocument();
+
+ // Wait for button to be enabled (ensures all state updates have settled)
+ await waitFor(() => {
+ expect(saveButton).not.toBeDisabled();
+ });
+
+ // Click save button
+ await user.click(saveButton);
+
+ // Wait for modal to appear
+ const okButton = await screen.findByRole('button', { name: /ok/i });
+ expect(okButton).toBeInTheDocument();
+
+ // Click OK button
+ await user.click(okButton);
+
+ // Verify API was called with empty S3 values (60 days)
+ await waitFor(() => {
+ expect(setRetentionApiV2).toHaveBeenCalledWith({
+ type: 'logs',
+ defaultTTLDays: 60,
+ coldStorageVolume: '',
+ coldStorageDurationDays: 0,
+ ttlConditions: [],
+ });
+ });
+ });
+ });
+
+ describe('Test 3: Save & Reload - Correct Display', () => {
+ it('should display retention values correctly after converting from hours', () => {
+ render(
+ <GeneralSettings
+ metricsTtlValuesPayload={mockMetricsRetention}
+ tracesTtlValuesPayload={mockTracesRetention}
+ logsTtlValuesPayload={mockLogsRetentionWithS3}
+ getAvailableDiskPayload={mockDisksWithS3}
+ metricsTtlValuesRefetch={jest.fn()}
+ tracesTtlValuesRefetch={jest.fn()}
+ logsTtlValuesRefetch={jest.fn()}
+ />,
+ );
+
+ // Find the Logs card
+ const logsCard = screen.getByText('Logs').closest('.ant-card');
+ const inputs = logsCard?.querySelectorAll('input[type="text"]');
+
+ // Total retention: 720 hours = 30 days = 1 month (displays as 1 Month)
+ const totalInput = inputs?.[0] as HTMLInputElement;
+ expect(totalInput.value).toBe('1');
+
+ // S3 retention: 24 day
+ const s3Input = inputs?.[1] as HTMLInputElement;
+ expect(s3Input.value).toBe('24');
+
+ // Verify dropdowns: total shows Months, S3 shows Days
+ const dropdowns = logsCard?.querySelectorAll('.ant-select-selection-item');
+ expect(dropdowns?.[0]).toHaveTextContent('Months');
+ expect(dropdowns?.[1]).toHaveTextContent('Days');
+ });
+ });
+});
diff --git a/frontend/src/container/GeneralSettings/utils.ts b/frontend/src/container/GeneralSettings/utils.ts
index b5dee55603..230e4f446d 100644
--- a/frontend/src/container/GeneralSettings/utils.ts
+++ b/frontend/src/container/GeneralSettings/utils.ts
@@ -34,12 +34,22 @@ interface ITimeUnitConversion {
value: number;
timeUnitValue: SettingPeriod;
}
+
+/**
+ * Converts hours value to the most relevant unit from the available units.
+ * @param value - The value in hours
+ * @param availableUnits - Optional array of available time units to consider. If not provided, all units are considered.
+ * @returns The converted value and the selected time unit
+ */
export const convertHoursValueToRelevantUnit = (
value: number,
+ availableUnits?: ITimeUnit[],
): ITimeUnitConversion => {
- if (value)
- for (let idx = TimeUnits.length - 1; idx >= 0; idx -= 1) {
- const timeUnit = TimeUnits[idx];
+ const unitsToConsider = availableUnits?.length ? availableUnits : TimeUnits;
+
+ if (value) {
+ for (let idx = unitsToConsider.length - 1; idx >= 0; idx -= 1) {
+ const timeUnit = unitsToConsider[idx];
const convertedValue = timeUnit.multiplier * value;
if (
@@ -49,7 +59,10 @@ export const convertHoursValueToRelevantUnit = (
return { value: convertedValue, timeUnitValue: timeUnit.value };
}
}
- return { value, timeUnitValue: TimeUnits[0].value };
+ }
+
+ // Fallback to the first available unit
+ return { value, timeUnitValue: unitsToConsider[0].value };
};
export const convertHoursValueToRelevantUnitString = (
diff --git a/frontend/src/types/api/settings/getRetention.ts b/frontend/src/types/api/settings/getRetention.ts
index c2043e2138..55d9cf45c2 100644
--- a/frontend/src/types/api/settings/getRetention.ts
+++ b/frontend/src/types/api/settings/getRetention.ts
@@ -19,8 +19,7 @@ export interface PayloadPropsTraces {
export interface PayloadPropsLogs {
version: 'v1' | 'v2';
default_ttl_days: number;
- logs_ttl_duration_hrs?: number;
- logs_move_ttl_duration_hrs?: number;
+ cold_storage_ttl_days?: number;
status: TStatus;
expected_logs_ttl_duration_hrs?: number;
expected_logs_move_ttl_duration_hrs?: number;
diff --git a/frontend/src/types/api/settings/setRetention.ts b/frontend/src/types/api/settings/setRetention.ts
index 01f965245c..43b83b2ebb 100644
--- a/frontend/src/types/api/settings/setRetention.ts
+++ b/frontend/src/types/api/settings/setRetention.ts
@@ -11,7 +11,7 @@ export interface PropsV2 {
type: TTTLType;
defaultTTLDays: number;
coldStorageVolume: string;
- coldStorageDuration: number;
+ coldStorageDurationDays: number;
ttlConditions: {
conditions: {
key: string;