Update VaultQueryHandler.ts with 3 attempts-write
This commit is contained in:
parent
44d996e7a4
commit
18af4e7d47
|
|
@ -273,16 +273,10 @@ export class VaultQueryHandler {
|
||||||
frontmatter: Record<string, any>,
|
frontmatter: Record<string, any>,
|
||||||
body: string
|
body: string
|
||||||
): Promise<WriteResult> {
|
): Promise<WriteResult> {
|
||||||
const file = this.app.vault.getAbstractFileByPath(path);
|
|
||||||
if (!(file instanceof TFile)) {
|
|
||||||
throw new Error(`Файл не найден для записи: ${path}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const yamlStr = this._serializeYaml(frontmatter);
|
const yamlStr = this._serializeYaml(frontmatter);
|
||||||
const newContent = `---\n${yamlStr}---\n\n${body.trim()}\n`;
|
const newContent = `---\n${yamlStr}---\n\n${body.trim()}\n`;
|
||||||
|
|
||||||
await this.app.vault.modify(file, newContent);
|
return this._writeFileWithRetry(path, newContent);
|
||||||
return { success: true, path };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
|
|
@ -297,26 +291,75 @@ export class VaultQueryHandler {
|
||||||
path: string,
|
path: string,
|
||||||
content: string
|
content: string
|
||||||
): Promise<WriteResult> {
|
): Promise<WriteResult> {
|
||||||
// Создаём папки если нужно
|
return this._writeFileWithRetry(path, content);
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Общий метод записи с повторными попытками
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private async _writeFileWithRetry(
|
||||||
|
path: string,
|
||||||
|
content: string,
|
||||||
|
maxAttempts = 3
|
||||||
|
): Promise<WriteResult> {
|
||||||
|
let lastError: Error | null = null;
|
||||||
|
|
||||||
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||||
|
try {
|
||||||
|
// --- Шаг 1: Запись ---
|
||||||
|
const existing = this.app.vault.getAbstractFileByPath(path);
|
||||||
|
|
||||||
|
if (existing instanceof TFile) {
|
||||||
|
await this.app.vault.modify(existing, content);
|
||||||
|
} else {
|
||||||
|
// Создать папки при необходимости
|
||||||
const folderPath = path.includes('/')
|
const folderPath = path.includes('/')
|
||||||
? path.substring(0, path.lastIndexOf('/'))
|
? path.substring(0, path.lastIndexOf('/'))
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
if (folderPath) {
|
if (folderPath) {
|
||||||
const folderExists = this.app.vault.getAbstractFileByPath(folderPath);
|
const folderExists = this.app.vault.getAbstractFileByPath(folderPath);
|
||||||
if (!folderExists) {
|
if (!folderExists) {
|
||||||
await this.app.vault.createFolder(folderPath);
|
await this.app.vault.createFolder(folderPath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const existing = this.app.vault.getAbstractFileByPath(path);
|
|
||||||
if (existing instanceof TFile) {
|
|
||||||
await this.app.vault.modify(existing, content);
|
|
||||||
} else {
|
|
||||||
await this.app.vault.create(path, content);
|
await this.app.vault.create(path, content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Шаг 2: Проверка (перечитываем и сравниваем) ---
|
||||||
|
const writtenFile = this.app.vault.getAbstractFileByPath(path);
|
||||||
|
if (!(writtenFile instanceof TFile)) {
|
||||||
|
throw new Error(`Файл не найден сразу после записи: ${path}`);
|
||||||
|
}
|
||||||
|
const writtenContent = await this.app.vault.read(writtenFile);
|
||||||
|
|
||||||
|
// Сравниваем, игнорируя возможные конечные переводы строк
|
||||||
|
if (writtenContent.trim() === content.trim()) {
|
||||||
|
// Успех
|
||||||
return { success: true, path };
|
return { success: true, path };
|
||||||
|
} else {
|
||||||
|
// Содержимое не совпало — ошибка
|
||||||
|
throw new Error(
|
||||||
|
`Содержимое файла не совпадает с записанным (попытка ${attempt})`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
lastError = err instanceof Error ? err : new Error(String(err));
|
||||||
|
console.warn(
|
||||||
|
`VaultQueryHandler: попытка ${attempt} записи ${path} не удалась:`,
|
||||||
|
lastError.message
|
||||||
|
);
|
||||||
|
if (attempt < maxAttempts) {
|
||||||
|
// Экспоненциальная задержка: 100, 200, 300 мс
|
||||||
|
const delay = 100 * attempt;
|
||||||
|
await new Promise(resolve => setTimeout(resolve, delay));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(
|
||||||
|
`Не удалось записать файл ${path} после ${maxAttempts} попыток: ${lastError?.message || 'неизвестная ошибка'}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user