diff --git a/app/components/DocumentListItem.tsx b/app/components/DocumentListItem.tsx
index 1f88889afd..e19e55c264 100644
--- a/app/components/DocumentListItem.tsx
+++ b/app/components/DocumentListItem.tsx
@@ -235,21 +235,6 @@ function DocumentListItem(
{t("Draft")}
)}
- {document.destroysInDays !== undefined && (
-
-
- {t("{{ count }} days", {
- count: document.destroysInDays,
- })}
-
-
- )}
{canStar && !isMobile && }
@@ -269,6 +254,23 @@ function DocumentListItem(
/>
+ {document.destroysInDays !== undefined && (
+
+
+
+ {t("{{ count }} days", {
+ count: document.destroysInDays,
+ })}
+
+
+
+ )}
- RetentionPeriodPresets.map((days) => ({
- type: "item",
- label:
- days === 0 ? t("Forever") : t("{{ count }} days", { count: days }),
- value: String(days),
- })) satisfies Option[],
- [t]
- );
-
const commentingOptions: Option[] = React.useMemo(
() =>
[
@@ -221,36 +194,6 @@ function Security() {
[saveData, team.preferences]
);
- const handleTrashRetentionChange = React.useCallback(
- async (value: string) => {
- const retentionDays = toRetentionPeriod(value);
- if (retentionDays === undefined) {
- return;
- }
- const preferences = {
- ...team.preferences,
- [TeamPreference.TrashRetentionDays]: retentionDays,
- };
- await saveData({ preferences });
- },
- [saveData, team.preferences]
- );
-
- const handleDataRetentionChange = React.useCallback(
- async (value: string) => {
- const retentionDays = toRetentionPeriod(value);
- if (retentionDays === undefined) {
- return;
- }
- const preferences = {
- ...team.preferences,
- [TeamPreference.DataRetentionDays]: retentionDays,
- };
- await saveData({ preferences });
- },
- [saveData, team.preferences]
- );
-
const handleCommentingChange = React.useCallback(
async (commenting: string) => {
const preferences = {
@@ -469,38 +412,6 @@ function Security() {
/>
)}
-
-
-
-
-
-
);
}
diff --git a/server/commands/documentLoader.ts b/server/commands/documentLoader.ts
index 1e535a5902..799a3debec 100644
--- a/server/commands/documentLoader.ts
+++ b/server/commands/documentLoader.ts
@@ -20,13 +20,9 @@ export default async function loadDocument({
includeState,
});
- if (!document) {
- throw NotFoundError();
- }
-
// Documents that have left the trash are pending permanent deletion, they are
// treated as if they no longer exist.
- if (document.isDestroyed) {
+ if (!document || document.isDestroyed) {
throw NotFoundError();
}
diff --git a/server/models/Document.ts b/server/models/Document.ts
index a251752323..3cabbd4558 100644
--- a/server/models/Document.ts
+++ b/server/models/Document.ts
@@ -9,6 +9,7 @@ import type {
ScopeOptions,
FindOptions,
ProjectionAlias,
+ Utils,
WhereOptions,
} from "sequelize";
import {
@@ -50,6 +51,7 @@ import type {
ImportableIntegrationService,
NavigationNode,
ProsemirrorData,
+ RetentionPreference,
SourceMetadata,
} from "@shared/types";
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
@@ -873,6 +875,44 @@ class Document extends ArchivableModel<
);
}
+ /**
+ * Builds a filter matching documents that belong to a team configured with
+ * the given retention period. Teams that have not set the preference are
+ * matched by the default period.
+ *
+ * Comparison is performed on the raw JSON text rather than casting to an
+ * integer so that an unexpected value stored against the preference cannot
+ * fail the query for every other team in the same batch.
+ *
+ * @param preference the retention preference to match on.
+ * @param retentionDays the retention period in days.
+ * @returns the where clause literal and the replacements it requires.
+ */
+ static retentionPeriodFilter(
+ preference: RetentionPreference,
+ retentionDays: number
+ ): { where: Utils.Literal; replacements: Record } {
+ const isDefault =
+ retentionDays === Team.getDefaultRetentionPeriod(preference);
+ const matchesPreference = isDefault
+ ? `(preferences->>:preference IS NULL OR preferences->>:preference = :retentionDaysText)`
+ : `preferences->>:preference = :retentionDaysText`;
+
+ return {
+ where: Sequelize.literal(
+ `EXISTS (
+ SELECT 1 FROM teams
+ WHERE teams.id = "document"."teamId"
+ AND ${matchesPreference}
+ )`
+ ),
+ replacements: {
+ preference,
+ retentionDaysText: String(retentionDays),
+ },
+ };
+ }
+
static withMembershipScope(
userId: string,
options?: FindOptions & { includeDrafts?: boolean }
diff --git a/server/models/Team.test.ts b/server/models/Team.test.ts
index d78108df38..86f57f3249 100644
--- a/server/models/Team.test.ts
+++ b/server/models/Team.test.ts
@@ -1,10 +1,18 @@
import { randomUUID } from "node:crypto";
+import type { MockInstance } from "vitest";
+import { vi } from "vitest";
+import {
+ RetentionPeriodPresets,
+ TeamPreferenceDefaults,
+} from "@shared/constants";
+import { TeamPreference } from "@shared/types";
import { Team } from "@server/models";
import {
buildTeam,
buildCollection,
buildAttachment,
} from "@server/test/factories";
+import { setCloudHosted, setSelfHosted } from "@server/test/support";
describe("Team", () => {
describe("findByDomain", () => {
@@ -144,4 +152,90 @@ describe("Team", () => {
expect(result).toEqual(attachment.canonicalUrl);
});
});
+
+ describe("retentionPeriods", () => {
+ it("should include every configurable period", () => {
+ for (const days of RetentionPeriodPresets.filter(
+ (preset) => preset > 0
+ )) {
+ expect(Team.retentionPeriods).toContain(days);
+ }
+ });
+
+ it("should exclude infinite retention", () => {
+ expect(Team.retentionPeriods).not.toContain(0);
+ });
+
+ it("should return periods in ascending order", () => {
+ const periods = Team.retentionPeriods;
+ expect([...periods].sort((a, b) => a - b)).toEqual([...periods]);
+ });
+ });
+
+ describe("getDefaultRetentionPeriod", () => {
+ it("should return the configured default", () => {
+ expect(
+ Team.getDefaultRetentionPeriod(TeamPreference.TrashRetentionDays)
+ ).toEqual(TeamPreferenceDefaults[TeamPreference.TrashRetentionDays]);
+ });
+ });
+
+ describe("getRetentionPeriodsInUse", () => {
+ let findOne: MockInstance;
+
+ afterEach(() => {
+ findOne?.mockRestore();
+ });
+
+ it("should return every period when cloud hosted", async () => {
+ setCloudHosted();
+ findOne = vi.spyOn(Team, "findOne");
+
+ expect(
+ await Team.getRetentionPeriodsInUse(TeamPreference.TrashRetentionDays)
+ ).toEqual(Team.retentionPeriods);
+ expect(findOne).not.toHaveBeenCalled();
+ });
+
+ it("should return only the period the team is configured with", async () => {
+ setSelfHosted();
+ const team = await buildTeam();
+ team.setPreference(TeamPreference.TrashRetentionDays, 365);
+ findOne = vi.spyOn(Team, "findOne").mockResolvedValue(team);
+
+ expect(
+ await Team.getRetentionPeriodsInUse(TeamPreference.TrashRetentionDays)
+ ).toEqual([365]);
+ });
+
+ it("should return the default period when the team has no preference", async () => {
+ setSelfHosted();
+ const team = await buildTeam();
+ findOne = vi.spyOn(Team, "findOne").mockResolvedValue(team);
+
+ expect(
+ await Team.getRetentionPeriodsInUse(TeamPreference.TrashRetentionDays)
+ ).toEqual([TeamPreferenceDefaults[TeamPreference.TrashRetentionDays]]);
+ });
+
+ it("should return no periods for infinite retention", async () => {
+ setSelfHosted();
+ const team = await buildTeam();
+ team.setPreference(TeamPreference.TrashRetentionDays, 0);
+ findOne = vi.spyOn(Team, "findOne").mockResolvedValue(team);
+
+ expect(
+ await Team.getRetentionPeriodsInUse(TeamPreference.TrashRetentionDays)
+ ).toEqual([]);
+ });
+
+ it("should return no periods when there is no team", async () => {
+ setSelfHosted();
+ findOne = vi.spyOn(Team, "findOne").mockResolvedValue(null);
+
+ expect(
+ await Team.getRetentionPeriodsInUse(TeamPreference.TrashRetentionDays)
+ ).toEqual([]);
+ });
+ });
});
diff --git a/server/models/Team.ts b/server/models/Team.ts
index 5eef983318..9162fbc287 100644
--- a/server/models/Team.ts
+++ b/server/models/Team.ts
@@ -25,8 +25,15 @@ import {
IsNumeric,
} from "sequelize-typescript";
import { isEmail } from "validator";
-import { TeamPreferenceDefaults } from "@shared/constants";
-import type { TeamPreferences } from "@shared/types";
+import {
+ RetentionPeriodPresets,
+ TeamPreferenceDefaults,
+} from "@shared/constants";
+import type {
+ RetentionPeriodPreset,
+ RetentionPreference,
+ TeamPreferences,
+} from "@shared/types";
import { TeamPreference, UserRole } from "@shared/types";
import {
getBaseDomain,
@@ -614,6 +621,57 @@ class Team extends ParanoidModel<
order: [["updatedAt", "DESC"]],
});
}
+
+ /**
+ * Every retention period, in days, that a team can be configured with.
+ * Periods of zero (infinite retention) are omitted as they never require
+ * processing.
+ */
+ static get retentionPeriods(): readonly number[] {
+ return [...RetentionPeriodPresets]
+ .filter((days) => days > 0)
+ .sort((a, b) => a - b);
+ }
+
+ /**
+ * The retention period applied to teams that have not set an explicit
+ * preference. Falls back to infinite retention, so a missing default can
+ * never cause data to be deleted sooner than intended.
+ *
+ * @param preference the retention preference to read.
+ * @returns the default retention period in days.
+ */
+ static getDefaultRetentionPeriod(
+ preference: RetentionPreference
+ ): RetentionPeriodPreset {
+ return TeamPreferenceDefaults[preference] ?? 0;
+ }
+
+ /**
+ * The retention periods, in days, that must be processed for the given
+ * preference.
+ *
+ * @param preference the retention preference to read.
+ * @returns a sorted list of retention periods in days.
+ */
+ static async getRetentionPeriodsInUse(
+ preference: RetentionPreference
+ ): Promise {
+ if (env.isCloudHosted) {
+ return this.retentionPeriods;
+ }
+
+ const team = await this.findOne({
+ attributes: ["id", "preferences"],
+ order: [["createdAt", "DESC"]],
+ });
+ if (!team) {
+ return [];
+ }
+
+ const days = Number(team.getPreference(preference));
+ return Number.isInteger(days) && days > 0 ? [days] : [];
+ }
}
export default Team;
diff --git a/server/queues/tasks/CleanupPermanentlyDeletedDocumentsByRetentionTask.ts b/server/queues/tasks/CleanupPermanentlyDeletedDocumentsByRetentionTask.ts
index 58fb4a3de8..430f34ced0 100644
--- a/server/queues/tasks/CleanupPermanentlyDeletedDocumentsByRetentionTask.ts
+++ b/server/queues/tasks/CleanupPermanentlyDeletedDocumentsByRetentionTask.ts
@@ -3,8 +3,7 @@ import { subDays } from "date-fns";
import documentPermanentDeleter from "@server/commands/documentPermanentDeleter";
import Logger from "@server/logging/Logger";
import { Document } from "@server/models";
-import type { RetentionPreference } from "@server/utils/retention";
-import { teamRetentionPeriodFilter } from "@server/utils/retention";
+import type { RetentionPreference } from "@shared/types";
import { TeamPreference } from "@shared/types";
import { BaseTask, TaskPriority } from "./base/BaseTask";
import type { PartitionInfo } from "./base/BaseTask";
@@ -35,11 +34,7 @@ export default class CleanupPermanentlyDeletedDocumentsByRetentionTask extends B
`Permanently destroying upto ${limit} documents past ${retentionDays} day retention timeout…`
);
- const team = teamRetentionPeriodFilter(
- preference,
- retentionDays,
- "document"
- );
+ const team = Document.retentionPeriodFilter(preference, retentionDays);
const documents = await Document.scope([
"withDrafts",
diff --git a/server/queues/tasks/CleanupPermanentlyDeletedDocumentsTask.ts b/server/queues/tasks/CleanupPermanentlyDeletedDocumentsTask.ts
index b118a0fed5..70432ee74d 100644
--- a/server/queues/tasks/CleanupPermanentlyDeletedDocumentsTask.ts
+++ b/server/queues/tasks/CleanupPermanentlyDeletedDocumentsTask.ts
@@ -1,5 +1,5 @@
import Logger from "@server/logging/Logger";
-import { getRetentionPeriodsInUse } from "@server/utils/retention";
+import { Team } from "@server/models";
import { TeamPreference } from "@shared/types";
import { Minute } from "@shared/utils/time";
import { TaskPriority } from "./base/BaseTask";
@@ -15,7 +15,7 @@ export default class CleanupPermanentlyDeletedDocumentsTask extends CronTask {
*/
public async perform(props: Props) {
const task = new CleanupPermanentlyDeletedDocumentsByRetentionTask();
- const retentionPeriods = await getRetentionPeriodsInUse(
+ const retentionPeriods = await Team.getRetentionPeriodsInUse(
TeamPreference.DataRetentionDays
);
diff --git a/server/queues/tasks/ExpireDocumentsInTrashByRetentionTask.ts b/server/queues/tasks/ExpireDocumentsInTrashByRetentionTask.ts
index fcce055573..803c70adce 100644
--- a/server/queues/tasks/ExpireDocumentsInTrashByRetentionTask.ts
+++ b/server/queues/tasks/ExpireDocumentsInTrashByRetentionTask.ts
@@ -2,8 +2,7 @@ import { Op } from "sequelize";
import { subDays } from "date-fns";
import Logger from "@server/logging/Logger";
import { Document } from "@server/models";
-import type { RetentionPreference } from "@server/utils/retention";
-import { teamRetentionPeriodFilter } from "@server/utils/retention";
+import type { RetentionPreference } from "@shared/types";
import { TeamPreference } from "@shared/types";
import type { PartitionInfo } from "./base/BaseTask";
import { BaseTask, TaskPriority } from "./base/BaseTask";
@@ -34,11 +33,7 @@ export default class ExpireDocumentsInTrashByRetentionTask extends BaseTask {
- it("should return the configured default", () => {
- expect(
- getDefaultRetentionPeriod(TeamPreference.TrashRetentionDays)
- ).toEqual(defaultRetentionDays);
- });
-});
-
-describe("getRetentionPeriodsInUse", () => {
- it("should always include the default period", async () => {
- const periods = await getRetentionPeriodsInUse(
- TeamPreference.TrashRetentionDays
- );
- expect(periods).toContain(defaultRetentionDays);
- });
-
- it("should include a period configured by a team", async () => {
- const team = await buildTeam();
- team.setPreference(TeamPreference.TrashRetentionDays, 365);
- await team.save();
-
- const periods = await getRetentionPeriodsInUse(
- TeamPreference.TrashRetentionDays
- );
- expect(periods).toContain(365);
- });
-
- it("should exclude infinite retention", async () => {
- const team = await buildTeam();
- team.setPreference(TeamPreference.TrashRetentionDays, 0);
- await team.save();
-
- const periods = await getRetentionPeriodsInUse(
- TeamPreference.TrashRetentionDays
- );
- expect(periods).not.toContain(0);
- });
-
- it("should ignore values that are not a whole number of days", async () => {
- const team = await buildTeam();
- await sequelize.query(
- `UPDATE teams SET preferences = jsonb_set(coalesce(preferences, '{}'::jsonb), :path, '"nonsense"') WHERE id = :id`,
- {
- replacements: {
- path: `{${TeamPreference.TrashRetentionDays}}`,
- id: team.id,
- },
- }
- );
-
- const periods = await getRetentionPeriodsInUse(
- TeamPreference.TrashRetentionDays
- );
- expect(periods.every((days) => Number.isInteger(days) && days > 0)).toBe(
- true
- );
- });
-
- it("should return periods in ascending order", async () => {
- const periods = await getRetentionPeriodsInUse(
- TeamPreference.TrashRetentionDays
- );
- expect([...periods].sort((a, b) => a - b)).toEqual(periods);
- });
-});
diff --git a/server/utils/retention.ts b/server/utils/retention.ts
deleted file mode 100644
index 6b43ad8673..0000000000
--- a/server/utils/retention.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import type { Utils } from "sequelize";
-import { QueryTypes, Sequelize } from "sequelize";
-import { TeamPreferenceDefaults } from "@shared/constants";
-import type { RetentionPeriodPreset, TeamPreference } from "@shared/types";
-import { sequelize } from "@server/storage/database";
-
-/** Team preferences that express a retention period, in days. */
-export type RetentionPreference =
- | TeamPreference.TrashRetentionDays
- | TeamPreference.DataRetentionDays;
-
-/**
- * The SQL alias of the table holding the `teamId` column being matched against.
- * Sequelize aliases a table by its model name when selecting, and by its table
- * name when updating.
- */
-type TeamOwnedAlias = "document" | "documents";
-
-/**
- * The retention period applied to teams that have not set an explicit
- * preference. Falls back to infinite retention, so a missing default can never
- * cause data to be deleted sooner than intended.
- *
- * @param preference the retention preference to read.
- * @returns the default retention period in days.
- */
-export function getDefaultRetentionPeriod(
- preference: RetentionPreference
-): RetentionPeriodPreset {
- return TeamPreferenceDefaults[preference] ?? 0;
-}
-
-/**
- * Returns every retention period, in days, that is currently in use across all
- * teams for the given preference. The default period is always included so that
- * teams without an explicit preference are covered, and periods of zero
- * (infinite retention) are omitted as they never require processing.
- *
- * Deriving the periods from the data rather than from a fixed list of presets
- * ensures teams are never silently skipped if the presets offered in the UI
- * change, or if a team holds a value that is no longer offered.
- *
- * @param preference the retention preference to read.
- * @returns a sorted list of retention periods in days.
- */
-export async function getRetentionPeriodsInUse(
- preference: RetentionPreference
-): Promise {
- const rows = await sequelize.query<{ days: string | null }>(
- `SELECT DISTINCT preferences->>:preference AS days FROM teams WHERE preferences->>:preference IS NOT NULL`,
- {
- type: QueryTypes.SELECT,
- replacements: { preference },
- }
- );
-
- const periods = new Set([getDefaultRetentionPeriod(preference)]);
-
- for (const row of rows) {
- const days = Number(row.days);
- // Preferences are free-form JSON, values that are not a positive whole
- // number of days cannot be acted on and are ignored.
- if (Number.isInteger(days) && days > 0) {
- periods.add(days);
- }
- }
-
- periods.delete(0);
-
- return [...periods].sort((a, b) => a - b);
-}
-
-/**
- * Builds a filter matching rows that belong to a team configured with the given
- * retention period. Teams that have not set the preference are matched by the
- * default period.
- *
- * Comparison is performed on the raw JSON text rather than casting to an integer
- * so that an unexpected value stored against the preference cannot fail the
- * query for every other team in the same batch.
- *
- * @param preference the retention preference to match on.
- * @param retentionDays the retention period in days.
- * @param alias the SQL alias of the table holding the `teamId` column.
- * @returns the where clause literal and the replacements it requires.
- */
-export function teamRetentionPeriodFilter(
- preference: RetentionPreference,
- retentionDays: number,
- alias: TeamOwnedAlias
-): { where: Utils.Literal; replacements: Record } {
- const isDefault = retentionDays === getDefaultRetentionPeriod(preference);
- const matchesPreference = isDefault
- ? `(preferences->>:preference IS NULL OR preferences->>:preference = :retentionDaysText)`
- : `preferences->>:preference = :retentionDaysText`;
-
- return {
- where: Sequelize.literal(
- `EXISTS (
- SELECT 1 FROM teams
- WHERE teams.id = "${alias}"."teamId"
- AND ${matchesPreference}
- )`
- ),
- replacements: {
- preference,
- retentionDaysText: String(retentionDays),
- },
- };
-}
diff --git a/shared/constants.ts b/shared/constants.ts
index bd4aa6dde7..09027f94ea 100644
--- a/shared/constants.ts
+++ b/shared/constants.ts
@@ -13,9 +13,7 @@ import {
} from "./types";
/** Allowed retention period values in days. 0 means infinite (never delete). */
-export const RetentionPeriodPresets: readonly RetentionPeriodPreset[] = [
- 0, 7, 14, 30, 90, 180, 365,
-];
+export const RetentionPeriodPresets = [0, 7, 14, 30, 90, 180, 365] as const;
/**
* Whether the given value is a retention period that can be configured.
diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json
index b725fe9a64..a3c69ab055 100644
--- a/shared/i18n/locales/en_US/translation.json
+++ b/shared/i18n/locales/en_US/translation.json
@@ -1474,7 +1474,6 @@
"This could be your real name, or a nickname — however you’d like people to refer to you.": "This could be your real name, or a nickname — however you’d like people to refer to you.",
"Members and guests": "Members and guests",
"No one": "No one",
- "Forever": "Forever",
"Are you sure you want to require invites?": "Are you sure you want to require invites?",
"New users will first need to be invited to create an account. Default role and Allowed domains will no longer apply.": "New users will first need to be invited to create an account. Default role and Allowed domains will no longer apply.",
"Settings that impact the access, security, and content of your workspace.": "Settings that impact the access, security, and content of your workspace.",
@@ -1498,10 +1497,6 @@
"Allow editors to create new collections within the workspace": "Allow editors to create new collections within the workspace",
"Workspace creation": "Workspace creation",
"Allow editors to create new workspaces": "Allow editors to create new workspaces",
- "Trash retention": "Trash retention",
- "How long deleted documents remain in the trash, where they can still be restored": "How long deleted documents remain in the trash, where they can still be restored",
- "Data retention": "Data retention",
- "How long documents are retained after leaving the trash, before they are permanently erased": "How long documents are retained after leaving the trash, before they are permanently erased",
"Could not load shares": "Could not load shares",
"Sharing is currently disabled.": "Sharing is currently disabled.",
"You can globally enable and disable public document sharing in the security settings.": "You can globally enable and disable public document sharing in the security settings.",
diff --git a/shared/types.ts b/shared/types.ts
index 77f57bf619..b42e4881c3 100644
--- a/shared/types.ts
+++ b/shared/types.ts
@@ -1,5 +1,7 @@
+import type { RetentionPeriodPresets } from "./constants";
+
/** Allowed retention period in days. 0 means infinite (never delete). */
-export type RetentionPeriodPreset = 0 | 7 | 14 | 30 | 90 | 180 | 365;
+export type RetentionPeriodPreset = (typeof RetentionPeriodPresets)[number];
/** Available user roles. */
export enum UserRole {
@@ -479,6 +481,11 @@ export enum TeamPreference {
DisabledEmbeds = "disabledEmbeds",
}
+/** Team preferences that express a retention period, in days. */
+export type RetentionPreference =
+ | TeamPreference.TrashRetentionDays
+ | TeamPreference.DataRetentionDays;
+
export type TeamPreferences = {
[TeamPreference.SeamlessEdit]?: boolean;
[TeamPreference.PublicBranding]?: boolean;