You're right, let me analyze this more deeply. I see several fundamental issues that need addressing:
Deep Analysis of Issues
1. Architectural Problems
- Mixed Abstractions:
fileUtils.ts mixes Obsidian Vault operations with Node.js filesystem operations
- Inconsistent Interfaces: Some functions return booleans, others throw, others return null
- Leaky Abstractions: The service class doesn't properly encapsulate filesystem complexity
- Duplicate Locking: Two different locking implementations for the same problem
2. Performance Issues
- Redundant Existence Checks: Multiple
exists() calls in file creation paths
- Inefficient Path Operations: Repeated normalization and parsing
- No Caching: Repeated folder existence checks
- Blocking Operations: Synchronous-style async operations
3. Robustness Issues
- Race Conditions: File creation logic has potential races even with locking
- Inconsistent Error Recovery: Some operations fail silently, others throw
- Resource Leaks: Directory handles not properly cleaned up
- Type Safety: Loose typing around error codes and filesystem operations
Comprehensive Refactor
1. Core Filesystem Abstraction (src/utils/filesystem/core.ts):
import { promises as fsp } from "node:fs";
import path from "node:path";
export enum FileSystemErrorCode {
NotFound = "ENOENT",
AccessDenied = "EACCES",
Permission = "EPERM",
IsDirectory = "EISDIR",
NotDirectory = "ENOTDIR",
AlreadyExists = "EEXIST",
}
export class FileSystemError extends Error {
constructor(
public readonly operation: string,
public readonly path: string,
public readonly code: FileSystemErrorCode | string,
message?: string,
) {
super(message || `${operation} failed on ${path}: ${code}`);
this.name = "FileSystemError";
}
static fromNodeError(operation: string, path: string, error: unknown): FileSystemError {
const nodeError = error as NodeJS.ErrnoException;
return new FileSystemError(
operation,
path,
nodeError.code || "UNKNOWN",
nodeError.message,
);
}
get isNotFound(): boolean {
return this.code === FileSystemErrorCode.NotFound;
}
get isPermissionDenied(): boolean {
return this.code === FileSystemErrorCode.AccessDenied ||
this.code === FileSystemErrorCode.Permission;
}
}
export interface FileSystemStats {
isFile(): boolean;
isDirectory(): boolean;
size: number;
mtime: Date;
}
export interface FileSystemAdapter {
exists(path: string): Promise<boolean>;
stat(path: string): Promise<FileSystemStats | null>;
readFile(path: string): Promise<string>;
writeFile(path: string, content: string | Uint8Array): Promise<void>;
mkdir(path: string, recursive?: boolean): Promise<void>;
readdir(path: string): AsyncIterable<string>;
}
2. Node.js Filesystem Adapter (src/utils/filesystem/nodeAdapter.ts):
import { promises as fsp } from "node:fs";
import path from "node:path";
import { FileSystemAdapter, FileSystemError, FileSystemStats } from "./core";
export class NodeFileSystemAdapter implements FileSystemAdapter {
private statCache = new Map<string, { stats: FileSystemStats | null; timestamp: number }>();
private readonly CACHE_TTL = 5000; // 5 seconds
async exists(filePath: string): Promise<boolean> {
try {
const stats = await this.stat(filePath);
return stats !== null;
} catch {
return false;
}
}
async stat(filePath: string): Promise<FileSystemStats | null> {
const cached = this.statCache.get(filePath);
if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {
return cached.stats;
}
try {
const stats = await fsp.stat(filePath);
const result: FileSystemStats = {
isFile: () => stats.isFile(),
isDirectory: () => stats.isDirectory(),
size: stats.size,
mtime: stats.mtime,
};
this.statCache.set(filePath, { stats: result, timestamp: Date.now() });
return result;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
this.statCache.set(filePath, { stats: null, timestamp: Date.now() });
return null;
}
throw FileSystemError.fromNodeError("stat", filePath, error);
}
}
async readFile(filePath: string): Promise<string> {
try {
return await fsp.readFile(filePath, "utf-8");
} catch (error) {
throw FileSystemError.fromNodeError("read", filePath, error);
}
}
async writeFile(filePath: string, content: string | Uint8Array): Promise<void> {
try {
await fsp.mkdir(path.dirname(filePath), { recursive: true });
await fsp.writeFile(filePath, content);
// Invalidate cache for this path and its parent directory
this.statCache.delete(filePath);
this.statCache.delete(path.dirname(filePath));
} catch (error) {
throw FileSystemError.fromNodeError("write", filePath, error);
}
}
async mkdir(dirPath: string, recursive = true): Promise<void> {
try {
await fsp.mkdir(dirPath, { recursive });
this.statCache.delete(dirPath);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") {
throw FileSystemError.fromNodeError("mkdir", dirPath, error);
}
}
}
async *readdir(dirPath: string): AsyncIterable<string> {
let dirHandle: import("node:fs").Dir | undefined;
try {
dirHandle = await fsp.opendir(dirPath);
for await (const dirent of dirHandle) {
yield dirent.name;
}
} catch (error) {
throw FileSystemError.fromNodeError("readdir", dirPath, error);
} finally {
await dirHandle?.close();
}
}
clearCache(): void {
this.statCache.clear();
}
}
3. Obsidian Vault Adapter (src/utils/filesystem/vaultAdapter.ts):
import { normalizePath, type TFile, type Vault } from "obsidian";
import { FileSystemAdapter, FileSystemError, FileSystemStats } from "./core";
export class VaultFileSystemAdapter implements FileSystemAdapter {
private folderCache = new Set<string>();
constructor(private vault: Vault) {}
async exists(path: string): Promise<boolean> {
const normalized = normalizePath(path);
return this.vault.adapter.exists(normalized);
}
async stat(path: string): Promise<FileSystemStats | null> {
const normalized = normalizePath(path);
try {
const stat = await this.vault.adapter.stat(normalized);
return {
isFile: () => stat.type === "file",
isDirectory: () => stat.type === "folder",
size: stat.size || 0,
mtime: new Date(stat.mtime || 0),
};
} catch {
return null;
}
}
async readFile(path: string): Promise<string> {
const normalized = normalizePath(path);
try {
return await this.vault.adapter.read(normalized);
} catch (error) {
throw new FileSystemError("read", normalized, "VAULT_ERROR", String(error));
}
}
async writeFile(path: string, content: string): Promise<void> {
const normalized = normalizePath(path);
try {
await this.vault.adapter.write(normalized, content);
} catch (error) {
throw new FileSystemError("write", normalized, "VAULT_ERROR", String(error));
}
}
async mkdir(path: string): Promise<void> {
const normalized = normalizePath(path);
if (this.folderCache.has(normalized)) {
return;
}
// Fast path: check in-memory representation
if (this.vault.getFolderByPath(normalized)) {
this.folderCache.add(normalized);
return;
}
try {
const stat = await this.vault.adapter.stat(normalized).catch(() => null);
if (stat?.type === "folder") {
this.folderCache.add(normalized);
return;
}
if (stat) {
throw new FileSystemError("mkdir", normalized, "EEXIST", "Path exists but is not a folder");
}
await this.vault.createFolder(normalized);
this.folderCache.add(normalized);
} catch (error) {
if (error instanceof FileSystemError) throw error;
throw new FileSystemError("mkdir", normalized, "VAULT_ERROR", String(error));
}
}
async *readdir(path: string): AsyncIterable<string> {
const normalized = normalizePath(path);
const folder = this.vault.getFolderByPath(normalized);
if (!folder) {
throw new FileSystemError("readdir", normalized, "ENOENT", "Folder not found");
}
for (const child of folder.children) {
yield child.name;
}
}
clearCache(): void {
this.folderCache.clear();
}
}
4. Unified File Operations Service (src/services/FileOperationsService.ts):
import { normalizePath, type TFile, type Vault } from "obsidian";
import { Notice } from "obsidian";
import { FileSystemAdapter, FileSystemError } from "src/utils/filesystem/core";
import { VaultFileSystemAdapter } from "src/utils/filesystem/vaultAdapter";
import { NodeFileSystemAdapter } from "src/utils/filesystem/nodeAdapter";
import { logger } from "src/utils/logging";
interface FileCreationOptions {
overwrite?: boolean;
createParents?: boolean;
maxAttempts?: number;
}
interface UniqueNameGenerator {
(baseName: string, attempt: number): string;
}
export class FileOperationsService {
private vaultAdapter: VaultFileSystemAdapter;
private nodeAdapter: NodeFileSystemAdapter;
private creationLocks = new Map<string, Promise<void>>();
constructor(private vault: Vault) {
this.vaultAdapter = new VaultFileSystemAdapter(vault);
this.nodeAdapter = new NodeFileSystemAdapter();
}
// --- Vault Operations ---
async ensureVaultFolder(folderPath: string): Promise<void> {
try {
await this.vaultAdapter.mkdir(folderPath);
} catch (error) {
this.handleError(error);
throw error;
}
}
async createVaultFileWithUniqueNameLocked(
baseDir: string,
filenameStem: string,
content: string,
options: FileCreationOptions = {},
): Promise<TFile> {
const lockKey = `${baseDir}/${filenameStem}`;
// Serialize file creation per directory/stem combination
const previousLock = this.creationLocks.get(lockKey) || Promise.resolve();
let resolveLock: () => void;
const currentLock = new Promise<void>(resolve => { resolveLock = resolve; });
this.creationLocks.set(lockKey, previousLock.then(() => currentLock));
try {
await previousLock;
return await this.createVaultFileWithUniqueName(baseDir, filenameStem, content, options);
} finally {
resolveLock!();
if (this.creationLocks.get(lockKey) === currentLock) {
this.creationLocks.delete(lockKey);
}
}
}
private async createVaultFileWithUniqueName(
baseDir: string,
filenameStem: string,
content: string,
options: FileCreationOptions = {},
): Promise<TFile> {
const { maxAttempts = 1000, createParents = true } = options;
if (createParents) {
await this.ensureVaultFolder(baseDir);
}
const nameGenerator: UniqueNameGenerator = (base, attempt) => {
const suffix = attempt === 0 ? "" : ` (${attempt})`;
return `${base}${suffix}.md`;
};
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const fileName = nameGenerator(filenameStem, attempt);
const fullPath = normalizePath(`${baseDir}/${fileName}`);
if (!(await this.vaultAdapter.exists(fullPath))) {
try {
return await this.vault.create(fullPath, content);
} catch (error) {
// If creation failed due to file existing (race condition), try next name
if (error instanceof Error && error.message.includes("already exists")) {
continue;
}
throw error;
}
}
}
// Fallback: use timestamp
const timestamp = Date.now().toString(36);
const fallbackName = `${filenameStem}-${timestamp}.md`;
const fallbackPath = normalizePath(`${baseDir}/${fallbackName}`);
return await this.vault.create(fallbackPath, content);
}
async generateUniqueVaultPath(
dir: string,
fileName: string,
maxAttempts = 1000,
): Promise<string> {
const { name: baseName, ext } = require("path").parse(fileName);
for (let i = 0; i < maxAttempts; i++) {
const suffix = i ? ` (${i})` : "";
const candidate = normalizePath(`${dir}/${baseName}${suffix}${ext}`);
if (!(await this.vaultAdapter.exists(candidate))) {
return candidate;
}
}
// Fallback with timestamp
const timestamp = Date.now().toString(36);
return normalizePath(`${dir}/${baseName}-${timestamp}${ext}`);
}
// --- Node.js Operations ---
async readNodeFile(filePath: string): Promise<string> {
try {
return await this.nodeAdapter.readFile(filePath);
} catch (error) {
this.handleError(error);
throw error;
}
}
async writeNodeFile(filePath: string, content: string | Uint8Array): Promise<void> {
try {
await this.nodeAdapter.writeFile(filePath, content);
} catch (error) {
this.handleError(error);
throw error;
}
}
async *iterateNodeDirectory(dirPath: string): AsyncIterable<string> {
try {
yield* this.nodeAdapter.readdir(dirPath);
} catch (error) {
this.handleError(error);
// Don't rethrow - just stop iteration
}
}
async getNodeStats(filePath: string) {
try {
return await this.nodeAdapter.stat(filePath);
} catch (error) {
if (error instanceof FileSystemError && error.isNotFound) {
return null;
}
this.handleError(error);
throw error;
}
}
// --- Utility Methods ---
toVaultRelativePath(rawPath: string): string {
return normalizePath(rawPath).replace(/^\/+/,