This commit is contained in:
Tom Moor committed 2026-08-16 16:15:36 -04:00
1 parent 04c1d99e82
commit d95884df1a
15 files changed
+236 -326

No files matched your search

+24 -15
View File
@@ -235,21 +235,6 @@ function DocumentListItem(
<Badge>{t("Draft")}</Badge>
</Tooltip>
)}
{document.destroysInDays !== undefined && (
<Tooltip
content={t(
"Will be permanently deleted in {{ count }} days unless restored",
{ count: document.destroysInDays }
)}
placement="top"
>
<Badge>
{t("{{ count }} days", {
count: document.destroysInDays,
})}
</Badge>
</Tooltip>
)}
{canStar && !isMobile && <StarButton document={document} />}
</Heading>
@@ -269,6 +254,23 @@ function DocumentListItem(
/>
</Content>
</Flex>
{document.destroysInDays !== undefined && (
<RetentionBadge>
<Tooltip
content={t(
"Will be permanently deleted in {{ count }} days unless restored",
{ count: document.destroysInDays }
)}
placement="top"
>
<Badge>
{t("{{ count }} days", {
count: document.destroysInDays,
})}
</Badge>
</Tooltip>
</RetentionBadge>
)}
<Actions>
<DocumentMenu
document={document}
@@ -336,6 +338,13 @@ const Content = styled.div`
min-width: 0;
`;
const RetentionBadge = styled.div`
display: flex;
align-items: center;
flex-shrink: 0;
margin-left: 8px;
`;
const Actions = styled(EventBoundary)`
display: none;
align-items: center;
-89
View File
@@ -6,11 +6,6 @@ import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import { toast } from "sonner";
import { errToString } from "@shared/utils/error";
import {
RetentionPeriodPresets,
isRetentionPeriodPreset,
} from "@shared/constants";
import type { RetentionPeriodPreset } from "@shared/types";
import { CommentingAccess, TeamPreference, EmailDisplay } from "@shared/types";
import ConfirmationDialog from "~/components/ConfirmationDialog";
import Heading from "~/components/Heading";
@@ -24,17 +19,6 @@ import useStores from "~/hooks/useStores";
import isCloudHosted from "~/utils/isCloudHosted";
import SettingRow from "./components/SettingRow";
/**
* Resolves a select value back to a supported retention period.
*
* @param value the raw value from the select input.
* @returns the retention period in days, or undefined if unsupported.
*/
function toRetentionPeriod(value: string): RetentionPeriodPreset | undefined {
const days = Number(value);
return isRetentionPeriodPreset(days) ? days : undefined;
}
function Security() {
const { dialogs } = useStores();
const team = useCurrentTeam();
@@ -88,17 +72,6 @@ function Security() {
[t]
);
const retentionOptions: Option[] = React.useMemo(
() =>
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() {
/>
</SettingRow>
)}
<SettingRow
label={t("Trash retention")}
name={TeamPreference.TrashRetentionDays}
description={t(
"How long deleted documents remain in the trash, where they can still be restored"
)}
>
<InputSelect
value={String(team.getPreference(TeamPreference.TrashRetentionDays))}
options={retentionOptions}
onChange={handleTrashRetentionChange}
label={t("Trash retention")}
labelHidden
short
/>
</SettingRow>
<SettingRow
label={t("Data retention")}
name={TeamPreference.DataRetentionDays}
description={t(
"How long documents are retained after leaving the trash, before they are permanently erased"
)}
>
<InputSelect
value={String(team.getPreference(TeamPreference.DataRetentionDays))}
options={retentionOptions}
onChange={handleDataRetentionChange}
label={t("Data retention")}
labelHidden
short
/>
</SettingRow>
</Scene>
);
}
+1 -5
View File
@@ -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();
}
+40
View File
@@ -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<string, string> } {
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<Document> & { includeDrafts?: boolean }
+94
View File
@@ -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([]);
});
});
});
+60 -2
View File
@@ -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<readonly number[]> {
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;
@@ -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",
@@ -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
);
@@ -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<Prop
`Marking upto ${limit} documents past ${retentionDays} day trash timeout as pending permanent deletion…`
);
const team = teamRetentionPeriodFilter(
preference,
retentionDays,
"document"
);
const team = Document.retentionPeriodFilter(preference, retentionDays);
// The batch is selected before updating as Postgres does not support a limit
// on UPDATE, and an unbounded update would hold locks across the entire table.
@@ -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 ExpireDocumentsInTrashTask extends CronTask {
*/
public async perform(props: Props) {
const task = new ExpireDocumentsInTrashByRetentionTask();
const retentionPeriods = await getRetentionPeriodsInUse(
const retentionPeriods = await Team.getRetentionPeriodsInUse(
TeamPreference.TrashRetentionDays
);
-78
View File
@@ -1,78 +0,0 @@
import { sequelize } from "@server/storage/database";
import { buildTeam } from "@server/test/factories";
import { TeamPreferenceDefaults } from "@shared/constants";
import { TeamPreference } from "@shared/types";
import {
getDefaultRetentionPeriod,
getRetentionPeriodsInUse,
} from "./retention";
const defaultRetentionDays = TeamPreferenceDefaults[
TeamPreference.TrashRetentionDays
] as number;
describe("getDefaultRetentionPeriod", () => {
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);
});
});
-110
View File
@@ -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<number[]> {
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<number>([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<string, string> } {
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),
},
};
}
+1 -3
View File
@@ -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.
@@ -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. <em>Default role</em> and <em>Allowed domains</em> will no longer apply.": "New users will first need to be invited to create an account. <em>Default role</em> and <em>Allowed domains</em> 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 <em>security settings</em>.": "You can globally enable and disable public document sharing in the <em>security settings</em>.",
+8 -1
View File
@@ -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;