Files
wekan/server/migrations/migrateAttachments.js
T
Lauri Ojansivu d56bb34490 Make large boards fast on 8 GB: load only what is visible, stop re-running every minicard, and stream big attachments.
On a seeded board of 4,000 cards, 12,000 comments, 20,000 checklist items
and 32,000 activities, served from FerretDB with SQLite as the Snap is:
closing a card took about 4 s and now takes 0.1 s, the board finished
loading in 17.6 s and now in 6.2 s, a card open re-ran about 7,700
computations and now about 1,000, and FerretDB used 13 s of CPU and 724 MB
while the board opened, now 3 s and 280 MB.

- The client data cache queued one more stop callback each time a helper
  re-ran, and every check asked Tracker for dependents, which on close was
  710 walks of 3 ms; there is now one callback per computation and key and
  one timer per key (imports/lib/dataCache.js).
- Opening a card writes the user's last-viewed card, and avatars, @mentions,
  list and swimlane headers read the whole user, so everything re-ran; they
  read only the fields they show. The comment, checklist and subtask indexes
  were one object every minicard depended on and are now per card
  (imports/lib/keyedGroupIndex.js).
- The lazy card window kept a full copy of every card of a list per window;
  it keeps the id and the sort keys, runs its id query once instead of five
  times, and sends comment text only when minicards show comments
  (server/publications/cardsWindow.js, models/lib/cardWindowFields.js).
  Comment reactions and legacy attachment lookups come with the opened card
  only.
- Attachment downloads honour Range for filesystem, GridFS and cloud
  storage (206, 416, If-Range); uploads to cloud storage are spooled to a
  temporary file and streamed instead of gathered into one Buffer; the API
  copy checks the size limit before reading; the legacy attachment
  migration streams, and no longer stores "[object Promise]" as a file; the
  board export no longer concatenates buffers quadratically.

The FerretDB fork pushes dotted-path filters such as meta.cardId down to
SQLite (they were each a full scan) and decodes only the fields a count
filters on. docs/Features/Admin-Panel/Problems/Large-Boards.md describes how
a large board loads and how to size a server with 8 GB of RAM.

Thanks to markusst1982 and xet7 !

Fixes #6745.
2026-10-09 13:28:08 +03:00

187 lines
6.4 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { ReactiveCache } from '/imports/reactiveCache';
import { getOldAttachmentData, getOldAttachmentStream } from '/models/lib/attachmentBackwardCompatibility';
import { addAttachmentFromStream } from '/models/lib/fileStoreStrategy';
import Attachments from '/models/attachments';
/**
* Migration script to convert old CollectionFS attachments to new Meteor-Files structure
* This script can be run to migrate all old attachments to the new format
*/
if (Meteor.isServer) {
// Resolve the board an attachment/card belongs to and verify the caller is
// allowed to act on it. Without this, any authenticated user could migrate
// (read + re-insert) attachments on boards they have no access to.
const requireBoardAccess = async (userId, boardId) => {
if (!boardId) {
throw new Meteor.Error('not-authorized', 'Attachment is not associated with a board');
}
const board = await ReactiveCache.getBoard(boardId);
const user = await ReactiveCache.getUser(userId);
if (!board || (!board.hasMember(userId) && !(user && user.isAdmin))) {
throw new Meteor.Error('not-authorized', 'User does not have access to this board');
}
};
Meteor.methods({
/**
* Migrate a single attachment from old to new structure
* @param {string} attachmentId - The old attachment ID
* @returns {Object} - Migration result
*/
async migrateAttachment(attachmentId) {
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'Must be logged in');
}
try {
// Get old attachment data
const oldAttachment = await getOldAttachmentData(attachmentId);
if (!oldAttachment) {
return { success: false, error: 'Old attachment not found' };
}
// Only allow migrating attachments on boards the caller can access.
await requireBoardAccess(this.userId, oldAttachment.meta && oldAttachment.meta.boardId);
// Check if already migrated
const existingAttachment = await ReactiveCache.getAttachment(attachmentId);
if (existingAttachment) {
return { success: true, message: 'Already migrated', attachmentId };
}
// #6745: stream the file out of GridFS into a new Meteor-Files
// attachment (through a temporary file on disk) instead of reading it
// into memory. This used to call getOldAttachmentDataBuffer() WITHOUT
// await: the whole file was read into memory in the background while
// `new File([fileData])` was handed the Promise, so the migrated
// attachment held the text "[object Promise]".
const readStream = await getOldAttachmentStream(attachmentId);
if (!readStream) {
return { success: false, error: 'Could not read file data from GridFS' };
}
const uploader = await addAttachmentFromStream(readStream, {
fileName: oldAttachment.name,
type: oldAttachment.type,
meta: oldAttachment.meta,
userId: oldAttachment.userId || this.userId,
size: oldAttachment.size,
});
if (uploader) {
return {
success: true,
message: 'Migration successful',
attachmentId,
newAttachmentId: uploader._id
};
} else {
return { success: false, error: 'Failed to create new attachment' };
}
} catch (error) {
console.error('Error migrating attachment:', error);
return { success: false, error: error.message };
}
},
/**
* Migrate all attachments for a specific card
* @param {string} cardId - The card ID
* @returns {Object} - Migration results
*/
async migrateCardAttachments(cardId) {
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'Must be logged in');
}
// Only allow migrating attachments on a card whose board the caller can access.
const card = await ReactiveCache.getCard(cardId);
await requireBoardAccess(this.userId, card && card.boardId);
const results = {
success: 0,
failed: 0,
errors: []
};
try {
// Get all old attachments for this card
const oldAttachments = await ReactiveCache.getAttachments({ 'meta.cardId': cardId });
for (const attachment of oldAttachments) {
const result = await Meteor.callAsync('migrateAttachment', attachment._id);
if (result.success) {
results.success++;
} else {
results.failed++;
results.errors.push({
attachmentId: attachment._id,
error: result.error
});
}
}
return results;
} catch (error) {
console.error('Error migrating card attachments:', error);
return { success: false, error: error.message };
}
},
/**
* Get migration status for attachments
* @param {string} cardId - The card ID (optional)
* @returns {Object} - Migration status
*/
async getAttachmentMigrationStatus(cardId) {
if (!this.userId) {
throw new Meteor.Error('not-authorized', 'Must be logged in');
}
// A card-scoped status read requires access to that card's board; the
// global (no card) status reads across all boards, so require admin.
if (cardId) {
const card = await ReactiveCache.getCard(cardId);
await requireBoardAccess(this.userId, card && card.boardId);
} else {
const user = await ReactiveCache.getUser(this.userId);
if (!(user && user.isAdmin)) {
throw new Meteor.Error('not-authorized', 'Only admins can read global migration status');
}
}
try {
const selector = cardId ? { 'meta.cardId': cardId } : {};
const allAttachments = await ReactiveCache.getAttachments(selector);
const status = {
total: allAttachments.length,
newStructure: 0,
oldStructure: 0,
mixed: false
};
for (const attachment of allAttachments) {
if (attachment.meta && attachment.meta.source === 'legacy') {
status.oldStructure++;
} else {
status.newStructure++;
}
}
status.mixed = status.oldStructure > 0 && status.newStructure > 0;
return status;
} catch (error) {
console.error('Error getting migration status:', error);
return { error: error.message };
}
}
});
}