feat(todo,app): files attached to tasks and comments

Halkyon's ADR 0043, D1, D3, D5 and D8: any file up to 100 MB, attached to
a task's description or to a comment, sealed as everything of Todo's.

Server: the attachment table, synced and sealed as the others, with the
sealed file's hash readable for the store; todoFiles hands halkyon_base
its rows, readable by their space's members, and takes sealed files
alone; the files no attachment names go daily. Its tests hold downloads
to the row's space, refuse a readable file and prune what no live row
names. Migration attachments: CREATE TABLE "attachment" with its indexes
and the foreign key to its space, cascading as every synced table's.

App: AttachmentRepository seals each file for its row, keeps it sealed
and opened in the person's folder, uploads it after each sync and fetches
it as it shows, both held back by Without files on mobile data but for a
file tapped. Under the description and a comment's text, a row of them:
pictures as thumbnails opening full-size, other files as chips opening in
the system's app, else saved; the paperclip beside the description and in the comment's
composer adds them, the composer holding them until it is sent. A task deleted takes its files
and its comments' along, a comment its own.

halkyon_app opens a file in the system's app (FileOpener): on Android
through its plugin and a FileProvider of its own class, sharing the
cache's halkyon_opened/ folder alone; on the desktop as a file: URI.

Whats-New: Attach files to a task's description or a comment with the paperclip: pictures show as thumbnails, other files open in their app.
Whats-New-De: Hänge mit der Büroklammer Dateien an die Beschreibung einer Aufgabe oder an einen Kommentar: Bilder erscheinen als Vorschau, andere Dateien öffnen sich in ihrer App.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Tizian 「ティツィアーン」 <raisondetredev@pm.me>
This commit is contained in:
Tizian 「ティツィアーン」 2026-11-11 01:17:22 +01:00
commit 3ca4b4308d
Signed by: raisondetredev
GPG key ID: 07F6FCF405488B64
9 changed files with 23300 additions and 62 deletions

View file

@ -0,0 +1,29 @@
### A file attached to a task's description or to a comment (Halkyon's ADR
### 0043, D8): its name, media type and size, and what it is attached to, in
### its sealed payload (ADR 0033, D5); the file itself is sealed too, kept
### in halkyon_base's store (D2) and fetched when shown. The instance sees
### that it exists, its size and the sealed file's hash, not what it is
### attached to. Never changed: deleted with what it is attached to, or on
### its own. Synced.
class: Attachment
table: attachment
database: sync
fields:
### The sealed file's SHA-256, in lowercase hex: its name in the store,
### which the server reads to serve it and to count and prune the files
### (`todo_files.dart`). The hash of sealed bytes says nothing of the file.
sha256: String
### The key it is sealed with (ADR 0002's envelope); never null in Todo,
### where everything is sealed.
keyId: String?
### The content, sealed: UTF-8 JSON with a `schemaVersion` once opened.
payload: ByteData
### The sealing's nonce (ADR 0002's envelope).
nonce: ByteData?
indexes:
# Deleting a space finds its rows through this index (see content_key).
attachment_space_idx:
fields: spaceId
# A space's live files, for the room counted and the pruning.
attachment_hash_idx:
fields: spaceId, sha256

View file

@ -0,0 +1,14 @@
import 'package:clock/clock.dart';
import 'package:halkyon_base_server/base.dart';
import 'package:serverpod/serverpod.dart';
/// Deletes the stored files nobody can reach any more (Halkyon's ADR 0043):
/// those no live attachment names, a week after they were last claimed; the
/// server schedules it daily when it starts (`schedulePruning`).
class FilePruningFutureCall extends FutureCall {
/// Prunes one batch and logs how many files went.
Future<void> pruneFiles(Session session) async {
final pruned = await pruneUnreferencedFiles(session, now: clock.now());
session.log('Pruned $pruned unreferenced files.');
}
}

View file

@ -0,0 +1,71 @@
import 'package:halkyon_base_server/base.dart';
import 'package:halkyon_todo_server/src/generated/protocol.dart';
import 'package:serverpod/serverpod.dart';
import 'package:serverpod_offline_sync_server/serverpod_offline_sync_server.dart';
/// Todo's files in halkyon_base's store (Halkyon's ADR 0043, D6): the
/// `attachment` rows name them, a file is read by the members of the space
/// its row is in, and every file is sealed, as every row is (ADR 0033, D5);
/// up to 100 MB, the module's default (D3).
const todoFiles = FileStore(
fileOfRow: _fileOfAttachment,
liveHashes: _liveAttachmentHashes,
accepts: FileStore.acceptsSealedOnly,
);
/// The file the attachment row [attachmentId] names, where the caller may
/// read its space: their own, or one they are a member of (ADR 0044); null
/// for a deleted row (the sync engine hides tombstones) and any other.
Future<StoredFileRef?> _fileOfAttachment(
Session session,
UuidValue attachmentId,
) async {
// SELECT * FROM "attachment" WHERE "id" = $1 (tombstones hidden)
final attachment = await Attachment.db.findById(session, attachmentId);
final spaceId = attachment?.spaceId;
// SELECT * FROM "offline_sync_spaces" WHERE "id" = $1
final space = spaceId == null
? null
: await OfflineSyncSpace.db.findById(session, spaceId);
final caller = UuidValue.withValidation(
session.authenticated!.userIdentifier,
);
if (attachment == null ||
space == null ||
!(space.uuidSpaceId == caller ||
await OfflineSyncSpaces(
session,
).roleOf(user: caller, space: space.uuidSpaceId) !=
null)) {
return null;
}
return (space: space.uuidSpaceId, sha256: attachment.sha256);
}
/// Which of [hashes] (every one, where null) the live attachment rows of
/// [space] name.
Future<Set<String>> _liveAttachmentHashes(
Session session,
UuidValue space,
Set<String>? hashes,
) async {
// SELECT "id" FROM "offline_sync_spaces" WHERE "uuidSpaceId" = $1
final spaceId = (await OfflineSyncSpace.db.findFirstRow(
session,
where: (t) => t.uuidSpaceId.equals(space),
))?.id;
if (spaceId == null) {
return const {};
}
// SELECT * FROM "attachment" WHERE "spaceId" = $1 [AND "sha256" IN …]
// (tombstones hidden)
return {
for (final attachment in await Attachment.db.find(
session,
where: (t) => hashes == null
? t.spaceId.equals(spaceId)
: t.spaceId.equals(spaceId) & t.sha256.inSet(hashes),
))
attachment.sha256,
};
}

View file

@ -0,0 +1,702 @@
/* AUTOMATICALLY GENERATED CODE DO NOT MODIFY */
/* To generate run: "serverpod generate" */
// ignore_for_file: implementation_imports
// ignore_for_file: library_private_types_in_public_api
// ignore_for_file: non_constant_identifier_names
// ignore_for_file: public_member_api_docs
// ignore_for_file: type_literal_in_constant_pattern
// ignore_for_file: use_super_parameters
// ignore_for_file: invalid_use_of_internal_member
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:typed_data' as _idt;
import 'package:serverpod/serverpod.dart' as _is;
/// A file attached to a task's description or to a comment (Halkyon's ADR
/// 0043, D8): its name, media type and size, and what it is attached to, in
/// its sealed payload (ADR 0033, D5); the file itself is sealed too, kept
/// in halkyon_base's store (D2) and fetched when shown. The instance sees
/// that it exists, its size and the sealed file's hash, not what it is
/// attached to. Never changed: deleted with what it is attached to, or on
/// its own. Synced.
abstract class Attachment
implements _is.TableRow<_is.UuidValue?>, _is.ProtocolSerialization {
Attachment._({
this.id,
this.spaceId,
required this.sha256,
this.keyId,
required this.payload,
this.nonce,
});
factory Attachment({
_is.UuidValue? id,
int? spaceId,
required String sha256,
String? keyId,
required _idt.ByteData payload,
_idt.ByteData? nonce,
}) = _AttachmentImpl;
factory Attachment.fromJson(Map<String, dynamic> jsonSerialization) {
return Attachment(
id: jsonSerialization['id'] == null
? null
: _is.UuidValueJsonExtension.fromJson(jsonSerialization['id']),
spaceId: jsonSerialization['spaceId'] as int?,
sha256: jsonSerialization['sha256'] as String,
keyId: jsonSerialization['keyId'] as String?,
payload: _is.ByteDataJsonExtension.fromJson(jsonSerialization['payload']),
nonce: jsonSerialization['nonce'] == null
? null
: _is.ByteDataJsonExtension.fromJson(jsonSerialization['nonce']),
);
}
static final t = AttachmentTable();
static const db = AttachmentRepository._();
@override
_is.UuidValue? id;
/// The space owning this row. Maintained by the sync engine.
int? spaceId;
/// The sealed file's SHA-256, in lowercase hex: its name in the store,
/// which the server reads to serve it and to count and prune the files
/// (`todo_files.dart`). The hash of sealed bytes says nothing of the file.
String sha256;
/// The key it is sealed with (ADR 0002's envelope); never null in Todo,
/// where everything is sealed.
String? keyId;
/// The content, sealed: UTF-8 JSON with a `schemaVersion` once opened.
_idt.ByteData payload;
/// The sealing's nonce (ADR 0002's envelope).
_idt.ByteData? nonce;
@override
_is.Table<_is.UuidValue?> get table => t;
/// Returns a shallow copy of this [Attachment]
/// with some or all fields replaced by the given arguments.
@_is.useResult
Attachment copyWith({
_is.UuidValue? id,
int? spaceId,
String? sha256,
String? keyId,
_idt.ByteData? payload,
_idt.ByteData? nonce,
});
@override
Map<String, dynamic> toJson() {
return {
'__className__': 'Attachment',
if (id != null) 'id': id?.toJson(),
if (spaceId != null) 'spaceId': spaceId,
'sha256': sha256,
if (keyId != null) 'keyId': keyId,
'payload': payload.toJson(),
if (nonce != null) 'nonce': nonce?.toJson(),
};
}
@override
Map<String, dynamic> toJsonForProtocol() {
return {
'__className__': 'Attachment',
if (id != null) 'id': id?.toJson(),
if (spaceId != null) 'spaceId': spaceId,
'sha256': sha256,
if (keyId != null) 'keyId': keyId,
'payload': payload.toJson(),
if (nonce != null) 'nonce': nonce?.toJson(),
};
}
static AttachmentInclude include() {
return AttachmentInclude._();
}
static AttachmentIncludeList includeList({
_is.WhereExpressionBuilder<AttachmentTable>? where,
int? limit,
int? offset,
_is.OrderByBuilder<AttachmentTable>? orderBy,
_is.OrderByListBuilder<AttachmentTable>? orderByList,
AttachmentInclude? include,
}) {
return AttachmentIncludeList._(
where: where,
limit: limit,
offset: offset,
orderBy: orderBy?.call(Attachment.t),
orderByList: orderByList?.call(Attachment.t),
include: include,
);
}
@override
String toString() {
return _is.SerializationManager.encode(this);
}
}
class _Undefined {}
class _AttachmentImpl extends Attachment {
_AttachmentImpl({
_is.UuidValue? id,
int? spaceId,
required String sha256,
String? keyId,
required _idt.ByteData payload,
_idt.ByteData? nonce,
}) : super._(
id: id,
spaceId: spaceId,
sha256: sha256,
keyId: keyId,
payload: payload,
nonce: nonce,
);
/// Returns a shallow copy of this [Attachment]
/// with some or all fields replaced by the given arguments.
@_is.useResult
@override
Attachment copyWith({
Object? id = _Undefined,
Object? spaceId = _Undefined,
String? sha256,
Object? keyId = _Undefined,
_idt.ByteData? payload,
Object? nonce = _Undefined,
}) {
return Attachment(
id: id is _is.UuidValue? ? id : this.id,
spaceId: spaceId is int? ? spaceId : this.spaceId,
sha256: sha256 ?? this.sha256,
keyId: keyId is String? ? keyId : this.keyId,
payload: payload ?? this.payload.clone(),
nonce: nonce is _idt.ByteData? ? nonce : this.nonce?.clone(),
);
}
}
class AttachmentUpdateTable extends _is.UpdateTable<AttachmentTable> {
AttachmentUpdateTable(super.table);
_is.ColumnValue<int, int> spaceId(int? value) => _is.ColumnValue(
table.spaceId,
value,
);
_is.ColumnValue<String, String> sha256(String value) => _is.ColumnValue(
table.sha256,
value,
);
_is.ColumnValue<String, String> keyId(String? value) => _is.ColumnValue(
table.keyId,
value,
);
_is.ColumnValue<_idt.ByteData, _idt.ByteData> payload(_idt.ByteData value) =>
_is.ColumnValue(
table.payload,
value,
);
_is.ColumnValue<_idt.ByteData, _idt.ByteData> nonce(_idt.ByteData? value) =>
_is.ColumnValue(
table.nonce,
value,
);
}
class AttachmentTable extends _is.Table<_is.UuidValue?> {
AttachmentTable({super.tableRelation}) : super(tableName: 'attachment') {
updateTable = AttachmentUpdateTable(this);
spaceId = _is.ColumnInt(
'spaceId',
this,
);
sha256 = _is.ColumnString(
'sha256',
this,
);
keyId = _is.ColumnString(
'keyId',
this,
);
payload = _is.ColumnByteData(
'payload',
this,
);
nonce = _is.ColumnByteData(
'nonce',
this,
);
}
late final AttachmentUpdateTable updateTable;
/// The space owning this row. Maintained by the sync engine.
late final _is.ColumnInt spaceId;
/// The sealed file's SHA-256, in lowercase hex: its name in the store,
/// which the server reads to serve it and to count and prune the files
/// (`todo_files.dart`). The hash of sealed bytes says nothing of the file.
late final _is.ColumnString sha256;
/// The key it is sealed with (ADR 0002's envelope); never null in Todo,
/// where everything is sealed.
late final _is.ColumnString keyId;
/// The content, sealed: UTF-8 JSON with a `schemaVersion` once opened.
late final _is.ColumnByteData payload;
/// The sealing's nonce (ADR 0002's envelope).
late final _is.ColumnByteData nonce;
@override
List<_is.Column> get columns => [
id,
spaceId,
sha256,
keyId,
payload,
nonce,
];
}
class AttachmentInclude extends _is.IncludeObject {
AttachmentInclude._();
@override
Map<String, _is.Include?> get includes => {};
@override
_is.Table<_is.UuidValue?> get table => Attachment.t;
}
class AttachmentIncludeList extends _is.IncludeList {
AttachmentIncludeList._({
_is.WhereExpressionBuilder<AttachmentTable>? where,
super.limit,
super.offset,
super.orderBy,
super.orderByList,
super.include,
}) {
super.where = where?.call(Attachment.t);
}
@override
Map<String, _is.Include?> get includes => include?.includes ?? {};
@override
_is.Table<_is.UuidValue?> get table => Attachment.t;
}
class AttachmentRepository {
const AttachmentRepository._();
/// Returns a list of [Attachment]s matching the given query parameters.
///
/// Use [where] to specify which items to include in the return value.
/// If none is specified, all items will be returned.
///
/// To specify the order of the items use [orderBy] or [orderByList]
/// when sorting by multiple columns.
///
/// The maximum number of items can be set by [limit]. If no limit is set,
/// all items matching the query will be returned.
///
/// [offset] defines how many items to skip, after which [limit] (or all)
/// items are read from the database.
///
/// ```dart
/// var persons = await Persons.db.find(
/// session,
/// where: (t) => t.lastName.equals('Jones'),
/// orderBy: (t) => t.firstName,
/// limit: 100,
/// );
/// ```
Future<List<Attachment>> find(
_is.DatabaseSession session, {
_is.WhereExpressionBuilder<AttachmentTable>? where,
int? limit,
int? offset,
_is.OrderByBuilder<AttachmentTable>? orderBy,
_is.OrderByListBuilder<AttachmentTable>? orderByList,
_is.Transaction? transaction,
_is.LockMode? lockMode,
_is.LockBehavior? lockBehavior,
}) async {
return session.db.find<Attachment>(
where: where?.call(Attachment.t),
orderBy: orderBy?.call(Attachment.t),
orderByList: orderByList?.call(Attachment.t),
limit: limit,
offset: offset,
transaction: transaction,
lockMode: lockMode,
lockBehavior: lockBehavior,
);
}
/// Returns the first matching [Attachment] matching the given query parameters.
///
/// Use [where] to specify which items to include in the return value.
/// If none is specified, all items will be returned.
///
/// To specify the order use [orderBy] or [orderByList]
/// when sorting by multiple columns.
///
/// [offset] defines how many items to skip, after which the next one will be picked.
///
/// ```dart
/// var youngestPerson = await Persons.db.findFirstRow(
/// session,
/// where: (t) => t.lastName.equals('Jones'),
/// orderBy: (t) => t.age,
/// );
/// ```
Future<Attachment?> findFirstRow(
_is.DatabaseSession session, {
_is.WhereExpressionBuilder<AttachmentTable>? where,
int? offset,
_is.OrderByBuilder<AttachmentTable>? orderBy,
_is.OrderByListBuilder<AttachmentTable>? orderByList,
_is.Transaction? transaction,
_is.LockMode? lockMode,
_is.LockBehavior? lockBehavior,
}) async {
return session.db.findFirstRow<Attachment>(
where: where?.call(Attachment.t),
orderBy: orderBy?.call(Attachment.t),
orderByList: orderByList?.call(Attachment.t),
offset: offset,
transaction: transaction,
lockMode: lockMode,
lockBehavior: lockBehavior,
);
}
/// Finds a single [Attachment] by its [id] or null if no such row exists.
Future<Attachment?> findById(
_is.DatabaseSession session,
_is.UuidValue id, {
_is.Transaction? transaction,
_is.LockMode? lockMode,
_is.LockBehavior? lockBehavior,
}) async {
return session.db.findById<Attachment>(
id,
transaction: transaction,
lockMode: lockMode,
lockBehavior: lockBehavior,
);
}
/// Inserts all [Attachment]s in the list and returns the inserted rows.
///
/// The returned [Attachment]s will have their `id` fields set.
///
/// This is an atomic operation, meaning that if one of the rows fails to
/// insert, none of the rows will be inserted.
///
/// If [ignoreConflicts] is set to `true`, rows that conflict with existing
/// rows are silently skipped, and only the successfully inserted rows are
/// returned.
///
/// If [noReturn] is set to `true`, the inserted rows are not read back from
/// the database and an empty list is returned. This avoids the overhead of
/// transferring and deserializing the rows when the result is not needed.
Future<List<Attachment>> insert(
_is.DatabaseSession session,
List<Attachment> rows, {
_is.Transaction? transaction,
bool ignoreConflicts = false,
bool noReturn = false,
}) async {
return session.db.insert<Attachment>(
rows,
transaction: transaction,
ignoreConflicts: ignoreConflicts,
noReturn: noReturn,
);
}
/// Inserts a single [Attachment] and returns the inserted row.
///
/// The returned [Attachment] will have its `id` field set.
Future<Attachment> insertRow(
_is.DatabaseSession session,
Attachment row, {
_is.Transaction? transaction,
}) async {
return session.db.insertRow<Attachment>(
row,
transaction: transaction,
);
}
/// Upserts all [Attachment]s in the list and returns the resulting rows.
///
/// If a row conflicts on the given [conflictColumns], the existing row is
/// updated with the new values. Otherwise, a new row is inserted.
///
/// If [updateColumns] is provided, only those columns will be updated on
/// conflict. If null, all non-conflict, non-id columns are updated.
///
/// If [updateWhere] is provided, the update only applies to rows matching the
/// given expression. Conflicting rows that don't match are skipped and not
/// returned, so the resulting list may be shorter than [rows].
///
/// The returned [Attachment]s will have their `id` fields set.
///
/// This is an atomic operation, meaning that if one of the rows fails,
/// none of the rows will be affected.
///
/// If [noReturn] is set to `true`, the resulting rows are not read back from
/// the database and an empty list is returned. This avoids the overhead of
/// transferring and deserializing the rows when the result is not needed.
Future<List<Attachment>> upsert(
_is.DatabaseSession session,
List<Attachment> rows, {
required _is.ColumnSelections<AttachmentTable> conflictColumns,
_is.ColumnSelections<AttachmentTable>? updateColumns,
_is.WhereExpressionBuilder<AttachmentTable>? updateWhere,
_is.Transaction? transaction,
bool noReturn = false,
}) async {
return session.db.upsert<Attachment>(
rows,
conflictColumns: conflictColumns(Attachment.t),
updateColumns: updateColumns?.call(Attachment.t),
updateWhere: updateWhere?.call(Attachment.t),
transaction: transaction,
noReturn: noReturn,
);
}
/// Upserts a single [Attachment] and returns the resulting row.
///
/// If the row conflicts on the given [conflictColumns], the existing row is
/// updated. Otherwise, a new row is inserted.
///
/// If [updateColumns] is provided, only those columns will be updated on
/// conflict. If null, all non-conflict, non-id columns are updated.
///
/// If [updateWhere] is provided, the update only applies when the existing
/// row matches the expression. Returns `null` if no row was affected — for
/// example when [updateWhere] does not match the conflicting row.
///
/// The returned [Attachment] will have its `id` field set.
Future<Attachment?> upsertRow(
_is.DatabaseSession session,
Attachment row, {
required _is.ColumnSelections<AttachmentTable> conflictColumns,
_is.ColumnSelections<AttachmentTable>? updateColumns,
_is.WhereExpressionBuilder<AttachmentTable>? updateWhere,
_is.Transaction? transaction,
}) async {
return session.db.upsertRow<Attachment>(
row,
conflictColumns: conflictColumns(Attachment.t),
updateColumns: updateColumns?.call(Attachment.t),
updateWhere: updateWhere?.call(Attachment.t),
transaction: transaction,
);
}
/// Updates all [Attachment]s in the list and returns the updated rows. If
/// [columns] is provided, only those columns will be updated. Defaults to
/// all columns.
/// This is an atomic operation, meaning that if one of the rows fails to
/// update, none of the rows will be updated.
///
/// If [noReturn] is set to `true`, the updated rows are not read back from
/// the database and an empty list is returned. This avoids the overhead of
/// transferring and deserializing the rows when the result is not needed.
Future<List<Attachment>> update(
_is.DatabaseSession session,
List<Attachment> rows, {
_is.ColumnSelections<AttachmentTable>? columns,
_is.Transaction? transaction,
bool noReturn = false,
}) async {
return session.db.update<Attachment>(
rows,
columns: columns?.call(Attachment.t),
transaction: transaction,
noReturn: noReturn,
);
}
/// Updates a single [Attachment]. The row needs to have its id set.
/// Optionally, a list of [columns] can be provided to only update those
/// columns. Defaults to all columns.
Future<Attachment> updateRow(
_is.DatabaseSession session,
Attachment row, {
_is.ColumnSelections<AttachmentTable>? columns,
_is.Transaction? transaction,
}) async {
return session.db.updateRow<Attachment>(
row,
columns: columns?.call(Attachment.t),
transaction: transaction,
);
}
/// Updates a single [Attachment] by its [id] with the specified [columnValues].
/// Returns the updated row or null if no row with the given id exists.
Future<Attachment?> updateById(
_is.DatabaseSession session,
_is.UuidValue id, {
required _is.ColumnValueListBuilder<AttachmentUpdateTable> columnValues,
_is.Transaction? transaction,
}) async {
return session.db.updateById<Attachment>(
id,
columnValues: columnValues(Attachment.t.updateTable),
transaction: transaction,
);
}
/// Updates all [Attachment]s matching the [where] expression with the specified [columnValues].
/// Returns the list of updated rows.
///
/// If [noReturn] is set to `true`, the updated rows are not read back from
/// the database and an empty list is returned. This avoids the overhead of
/// transferring and deserializing the rows when the result is not needed.
Future<List<Attachment>> updateWhere(
_is.DatabaseSession session, {
required _is.ColumnValueListBuilder<AttachmentUpdateTable> columnValues,
required _is.WhereExpressionBuilder<AttachmentTable> where,
int? limit,
int? offset,
_is.OrderByBuilder<AttachmentTable>? orderBy,
_is.OrderByListBuilder<AttachmentTable>? orderByList,
_is.Transaction? transaction,
bool noReturn = false,
}) async {
return session.db.updateWhere<Attachment>(
columnValues: columnValues(Attachment.t.updateTable),
where: where(Attachment.t),
limit: limit,
offset: offset,
orderBy: orderBy?.call(Attachment.t),
orderByList: orderByList?.call(Attachment.t),
transaction: transaction,
noReturn: noReturn,
);
}
/// Deletes all [Attachment]s in the list and returns the deleted rows.
///
/// To specify the order of the returned rows use [orderBy] or [orderByList]
/// when sorting by multiple columns.
///
/// This is an atomic operation, meaning that if one of the rows fail to
/// be deleted, none of the rows will be deleted.
///
/// If [noReturn] is set to `true`, the deleted rows are not read back from
/// the database and an empty list is returned. This avoids the overhead of
/// transferring and deserializing the rows when the result is not needed.
Future<List<Attachment>> delete(
_is.DatabaseSession session,
List<Attachment> rows, {
_is.OrderByBuilder<AttachmentTable>? orderBy,
_is.OrderByListBuilder<AttachmentTable>? orderByList,
_is.Transaction? transaction,
bool noReturn = false,
}) async {
return session.db.delete<Attachment>(
rows,
orderBy: orderBy?.call(Attachment.t),
orderByList: orderByList?.call(Attachment.t),
transaction: transaction,
noReturn: noReturn,
);
}
/// Deletes a single [Attachment].
Future<Attachment> deleteRow(
_is.DatabaseSession session,
Attachment row, {
_is.Transaction? transaction,
}) async {
return session.db.deleteRow<Attachment>(
row,
transaction: transaction,
);
}
/// Deletes all rows matching the [where] expression.
///
/// To specify the order of the returned rows use [orderBy] or [orderByList]
/// when sorting by multiple columns.
///
/// If [noReturn] is set to `true`, the deleted rows are not read back from
/// the database and an empty list is returned. This avoids the overhead of
/// transferring and deserializing the rows when the result is not needed.
Future<List<Attachment>> deleteWhere(
_is.DatabaseSession session, {
required _is.WhereExpressionBuilder<AttachmentTable> where,
_is.OrderByBuilder<AttachmentTable>? orderBy,
_is.OrderByListBuilder<AttachmentTable>? orderByList,
_is.Transaction? transaction,
bool noReturn = false,
}) async {
return session.db.deleteWhere<Attachment>(
where: where(Attachment.t),
orderBy: orderBy?.call(Attachment.t),
orderByList: orderByList?.call(Attachment.t),
transaction: transaction,
noReturn: noReturn,
);
}
/// Counts the number of rows matching the [where] expression. If omitted,
/// will return the count of all rows in the table.
Future<int> count(
_is.DatabaseSession session, {
_is.WhereExpressionBuilder<AttachmentTable>? where,
int? limit,
_is.Transaction? transaction,
}) async {
return session.db.count<Attachment>(
where: where?.call(Attachment.t),
limit: limit,
transaction: transaction,
);
}
/// Acquires row-level locks on [Attachment] rows matching the [where] expression.
Future<void> lockRows(
_is.DatabaseSession session, {
required _is.WhereExpressionBuilder<AttachmentTable> where,
required _is.LockMode lockMode,
required _is.Transaction transaction,
_is.LockBehavior lockBehavior = _is.LockBehavior.wait,
}) async {
return session.db.lockRows<Attachment>(
where: where(Attachment.t),
lockMode: lockMode,
lockBehavior: lockBehavior,
transaction: transaction,
);
}
}

View file

@ -14,6 +14,7 @@
import 'dart:async' as _ida;
import 'package:clock/clock.dart' as _io0w16m8;
import 'package:serverpod/serverpod.dart' as _is;
import '../attachment/file_pruning_future_call.dart' as _irygz6s8;
import '../pruning_future_call.dart' as _ibrplims;
/// Invokes a future call.
@ -58,6 +59,7 @@ class FutureCalls extends _is.FutureCallDispatch<_FutureCallRef> {
String serverId,
) {
var registeredFutureCalls = <String, _is.InvokableFutureCall>{
'FilePruningPruneFilesFutureCall': FilePruningPruneFilesFutureCall(),
'PruningPruneAccountsFutureCall': PruningPruneAccountsFutureCall(),
'PruningForgetSignUpAttemptsFutureCall':
PruningForgetSignUpAttemptsFutureCall(),
@ -185,9 +187,24 @@ class _FutureCallRef {
final _InvokeFutureCall _invokeFutureCall;
late final filePruning = _FilePruningFutureCallDispatcher(_invokeFutureCall);
late final pruning = _PruningFutureCallDispatcher(_invokeFutureCall);
}
class _FilePruningFutureCallDispatcher {
_FilePruningFutureCallDispatcher(this._invokeFutureCall);
final _InvokeFutureCall _invokeFutureCall;
Future<void> pruneFiles() {
return _invokeFutureCall(
'FilePruningPruneFilesFutureCall',
null,
);
}
}
class _PruningFutureCallDispatcher {
_PruningFutureCallDispatcher(this._invokeFutureCall);
@ -222,6 +239,18 @@ class _PruningFutureCallDispatcher {
}
}
/// Prunes one batch and logs how many files went.
class FilePruningPruneFilesFutureCall extends _is.FutureCall
implements _is.InvokableFutureCall {
@override
_ida.Future<void> invoke(
_is.Session session,
_is.SerializableModel? object,
) async {
await _irygz6s8.FilePruningFutureCall().pruneFiles(session);
}
}
/// Prunes one batch of anonymous accounts and logs how many people went,
/// forgets the resets that lapsed (ADR 0017) and the assistants' figures
/// past their 3 months (Learn's ADR 0021, D41), and deletes the new accounts left

View file

@ -25,6 +25,7 @@ import 'package:serverpod_auth_idp_server/serverpod_auth_idp_server.dart'
as _iais;
import 'package:serverpod_offline_sync_server/serverpod_offline_sync_server.dart'
as _izehhkf5;
import 'attachment/attachment.dart' as _imhw6pbz;
import 'comment/task_comment.dart' as _i68ws957;
import 'filter/saved_filter.dart' as _i9q9fhid;
import 'label/label.dart' as _ivak08z4;
@ -39,6 +40,7 @@ import 'settings/todo_settings.dart' as _icak60vd;
import 'task/task.dart' as _ib4f8uyw;
import 'weather/forecast_hour.dart' as _i1l0g3o2;
import 'weather/weather_refused.dart' as _ieu1vbq0;
export 'attachment/attachment.dart';
export 'comment/task_comment.dart';
export 'filter/saved_filter.dart';
export 'label/label.dart';
@ -63,6 +65,96 @@ class Protocol extends _is.DatabaseSerializationManager {
static final Protocol _instance = Protocol._().._registerHostProtocols();
static List<_isp.TableDefinition> get targetTableDefinitions => [
_isp.TableDefinition(
name: 'attachment',
dartName: 'Attachment',
schema: 'public',
module: 'halkyon_todo',
columns: [
_isp.ColumnDefinition(
name: 'id',
columnType: _isp.ColumnType.uuid,
isNullable: false,
dartType: 'UuidValue?',
columnDefault: 'random_v7',
),
_isp.ColumnDefinition(
name: 'spaceId',
columnType: _isp.ColumnType.bigint,
isNullable: true,
dartType: 'int?',
),
_isp.ColumnDefinition(
name: 'sha256',
columnType: _isp.ColumnType.text,
isNullable: false,
dartType: 'String',
),
_isp.ColumnDefinition(
name: 'keyId',
columnType: _isp.ColumnType.text,
isNullable: true,
dartType: 'String?',
),
_isp.ColumnDefinition(
name: 'payload',
columnType: _isp.ColumnType.bytea,
isNullable: false,
dartType: 'dart:typed_data:ByteData',
),
_isp.ColumnDefinition(
name: 'nonce',
columnType: _isp.ColumnType.bytea,
isNullable: true,
dartType: 'dart:typed_data:ByteData?',
),
],
foreignKeys: [
_isp.ForeignKeyDefinition(
constraintName: 'attachment_fk_0',
columns: ['spaceId'],
referenceTable: 'offline_sync_spaces',
referenceTableSchema: 'public',
referenceColumns: ['id'],
onUpdate: _isp.ForeignKeyAction.noAction,
onDelete: _isp.ForeignKeyAction.cascade,
matchType: null,
),
],
indexes: [
_isp.IndexDefinition(
indexName: 'attachment_space_idx',
tableSpace: null,
elements: [
_isp.IndexElementDefinition(
type: _isp.IndexElementDefinitionType.column,
definition: 'spaceId',
),
],
type: 'btree',
isUnique: false,
isPrimary: false,
),
_isp.IndexDefinition(
indexName: 'attachment_hash_idx',
tableSpace: null,
elements: [
_isp.IndexElementDefinition(
type: _isp.IndexElementDefinitionType.column,
definition: 'spaceId',
),
_isp.IndexElementDefinition(
type: _isp.IndexElementDefinitionType.column,
definition: 'sha256',
),
],
type: 'btree',
isUnique: false,
isPrimary: false,
),
],
managed: true,
),
_isp.TableDefinition(
name: 'content_key',
dartName: 'ContentKey',
@ -628,6 +720,9 @@ class Protocol extends _is.DatabaseSerializationManager {
}
}
if (t == _imhw6pbz.Attachment) {
return _imhw6pbz.Attachment.fromJson(data) as T;
}
if (t == _i68ws957.TaskComment) {
return _i68ws957.TaskComment.fromJson(data) as T;
}
@ -670,6 +765,9 @@ class Protocol extends _is.DatabaseSerializationManager {
if (t == _ieu1vbq0.WeatherRefused) {
return _ieu1vbq0.WeatherRefused.fromJson(data) as T;
}
if (t == _is.getType<_imhw6pbz.Attachment?>()) {
return (data != null ? _imhw6pbz.Attachment.fromJson(data) : null) as T;
}
if (t == _is.getType<_i68ws957.TaskComment?>()) {
return (data != null ? _i68ws957.TaskComment.fromJson(data) : null) as T;
}
@ -751,6 +849,7 @@ class Protocol extends _is.DatabaseSerializationManager {
static String? getClassNameForType(Type type) {
return switch (type) {
_imhw6pbz.Attachment => 'Attachment',
_i68ws957.TaskComment => 'TaskComment',
_i9q9fhid.SavedFilter => 'SavedFilter',
_ivak08z4.Label => 'Label',
@ -782,6 +881,8 @@ class Protocol extends _is.DatabaseSerializationManager {
}
switch (data) {
case _imhw6pbz.Attachment():
return 'Attachment';
case _i68ws957.TaskComment():
return 'TaskComment';
case _i9q9fhid.SavedFilter():
@ -850,6 +951,9 @@ class Protocol extends _is.DatabaseSerializationManager {
if (dataClassName is! String) {
return super.deserializeByClassName(data);
}
if (dataClassName == 'Attachment') {
return deserialize<_imhw6pbz.Attachment>(data['data']);
}
if (dataClassName == 'TaskComment') {
return deserialize<_i68ws957.TaskComment>(data['data']);
}
@ -966,6 +1070,8 @@ class Protocol extends _is.DatabaseSerializationManager {
}
}
switch (t) {
case _imhw6pbz.Attachment:
return _imhw6pbz.Attachment.t;
case _i68ws957.TaskComment:
return _i68ws957.TaskComment.t;
case _i9q9fhid.SavedFilter:

View file

@ -11,6 +11,7 @@
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:serverpod/serverpod.dart' as _is;
import 'attachment/attachment.dart' as _imhw6pbz;
import 'comment/task_comment.dart' as _i68ws957;
import 'filter/saved_filter.dart' as _i9q9fhid;
import 'label/label.dart' as _ivak08z4;
@ -24,6 +25,7 @@ import 'task/task.dart' as _ib4f8uyw;
/// `serverpod_offline_sync` package, including the ones owned by modules and
/// shared packages.
final List<_is.Table> syncTables = [
_imhw6pbz.Attachment.t,
_imed3x5d.ContentKey.t,
_ivak08z4.Label.t,
_i9c44spp.Project.t,

View file

@ -16,19 +16,24 @@ const _deletionNotices = 'tell-members-of-deletions';
/// The identifier of the daily deleting of accounts the register forgot.
const _deletedAccounts = 'forget-deleted-accounts';
/// The identifier of the daily pruning of files (Halkyon's ADR 0043).
const _filePruning = 'prune-unreferenced-files';
/// The future calls [schedulePruning] keeps scheduled, by their identifiers.
const pruningIdentifiers = [
_pruning,
_attemptPruning,
_deletionNotices,
_deletedAccounts,
_filePruning,
];
/// Schedules the pruning (`PruningFutureCall`): the anonymous accounts left
/// from before daily, sign-up attempts and expired email codes hourly, and the instance's
/// accounts (ADR 0016): the register's deletions its members haven't
/// confirmed hourly, a member's people the register forgot daily (each does
/// nothing in the other mode). Scheduling always adds an entry, so the
/// nothing in the other mode), and the files no attachment names any more
/// daily (`FilePruningFutureCall`). Scheduling always adds an entry, so the
/// previous one goes first, and starting the server again leaves one of
/// each; the one scheduled under the pruning's earlier name, which would
/// call nothing, goes too.
@ -61,4 +66,11 @@ Future<void> schedulePruning(Serverpod pod) async {
.cron('37 3 * * *')
.pruning
.forgetDeletedAccounts();
await pod.futureCalls.cancel(_filePruning);
await pod.futureCalls
.callRecurring(identifier: _filePruning)
.cron('47 3 * * *')
.filePruning
.pruneFiles();
}

View file

@ -1,4 +1,5 @@
import 'package:halkyon_base_server/base.dart';
import 'package:halkyon_todo_server/src/attachment/todo_files.dart';
import 'package:halkyon_todo_server/src/todo_data.dart';
/// Where this project's source is published, which the instance names
@ -21,6 +22,7 @@ const minimumAppBuild = 1;
/// with them ([deleteTodoData]). It holds the instance's
/// register, or is a member of the one [accounts] names (ADR 0016; the
/// server reads it from the operator's environment, `ACCOUNT_REGISTER_URL`).
/// It keeps the files attached to tasks and comments ([todoFiles], ADR 0043).
/// The server sets it up before it starts (`server.dart`), and so do its
/// tests.
HalkyonBase todoBase({AccountsMode accounts = const HoldsRegister()}) =>
@ -31,4 +33,5 @@ HalkyonBase todoBase({AccountsMode accounts = const HoldsRegister()}) =>
minimumAppBuild: minimumAppBuild,
deletePersonData: const [deleteTodoData],
accounts: accounts,
files: todoFiles,
);