using System;
using System.IO;
namespace Notify.Ipc;
///
/// Host 侧:监视 spool 目录,新文件出现即消费并回调
///
public sealed class SpoolWatcher
{
private readonly Action _onMessage;
private FileSystemWatcher? _watcher;
public SpoolWatcher(Action onMessage) => _onMessage = onMessage;
public void Start()
{
Directory.CreateDirectory(NotificationSpool.Dir);
// 先补弹启动前堆积的请求
NotificationSpool.DrainExisting(_onMessage);
_watcher = new FileSystemWatcher(NotificationSpool.Dir, "*.json")
{
NotifyFilter = NotifyFilters.FileName,
EnableRaisingEvents = true,
};
_watcher.Created += OnCreated;
_watcher.Renamed += OnRenamed;
}
private void OnCreated(object sender, FileSystemEventArgs e) => Handle(e.FullPath);
private void OnRenamed(object sender, RenamedEventArgs e) => Handle(e.FullPath);
private void Handle(string path)
{
if (NotificationSpool.ReadAndRemove(path) is { } msg)
{
_onMessage(msg);
}
}
}