perf(library): memoize scan parses per save (#143)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Every FSEvents change — each 1 s autosave echo — ran Post.scan over the whole library: read + frontmatter parse + title per post.md, O(library bytes) per save cycle while writing, and the posts array was replaced unconditionally, so every observing pane regrouped and re-rendered even when nothing changed. Post.scan now takes an optional PostScanCache (path+mtime+size-keyed parse memo, nil default — every other caller unchanged): the readdir walk stays the truth, only changed files are read and re-parsed. The stamp is captured BEFORE the read and keys the store, so a mid-scan rewrite can never be pinned as fresh — a late overlapping store keys its own pre-read stamp and the next scan misses (review-caught race, pinned by a same-size-rewrite test). rescan skips the posts assignment when the scan equals the current list; @Observable invalidates on assignment regardless of equality, so panes stop re-rendering on the app's own autosave echoes. Deliberately skipped (measured cold): folder(of:) caching (stat-only walk) and refreshCards throttling (O(open piece), card surfacing depends on it). Closes #143
This commit is contained in:
1 parent
cc317b65b9
commit
a2f6dc1653
9 files changed
+287
-39
No files matched your search
+134
-33
@@ -117,7 +117,10 @@ nonisolated struct Post: Identifiable, Equatable {
|
||||
/// Same skip rules at both levels: symlinks, hidden dirs, loose files;
|
||||
/// folders without `post.md` (lazy) aren't Posts; a malformed folder
|
||||
/// can't crash the list. Read-only for #17.
|
||||
static func scan(home: URL) -> [Post] {
|
||||
/// #143: pass a `cache` to reuse parses of files whose path, mtime,
|
||||
/// and size are unchanged (nil, the default, reads everything —
|
||||
/// every existing caller's behavior).
|
||||
static func scan(home: URL, cache: PostScanCache? = nil) -> [Post] {
|
||||
var posts: [Post] = []
|
||||
// #107 audit: duplicate ids can appear on disk (Finder copy across
|
||||
// projects, partial restore) — first-wins dedupe, in the SAME
|
||||
@@ -145,45 +148,69 @@ nonisolated struct Post: Identifiable, Equatable {
|
||||
guard pieceValues?.isDirectory ?? false, !(pieceValues?.isSymbolicLink ?? false),
|
||||
!dir.lastPathComponent.hasPrefix(".") else { continue }
|
||||
let fileURL = dir.appendingPathComponent("post.md")
|
||||
guard let text = try? String(contentsOf: fileURL, encoding: .utf8), seen.insert(dir.lastPathComponent).inserted else { continue }
|
||||
let frontmatter = frontmatter(of: text)
|
||||
let origin = Origin(rawValue: frontmatter["origin"] ?? "") ?? .writer
|
||||
let type = ContentType(rawValue: frontmatter["type"] ?? "") ?? .post
|
||||
posts.append(
|
||||
Post(
|
||||
id: dir.lastPathComponent,
|
||||
title: title(of: text),
|
||||
passState: PassState(rawValue: frontmatter["pass_state"] ?? "") ?? .firstDraft,
|
||||
origin: origin,
|
||||
type: type,
|
||||
project: projectDir.lastPathComponent,
|
||||
isArchived: isArchived,
|
||||
// #33: the remembered Micro.blog draft URL —
|
||||
// one flat key, read leniently like the rest.
|
||||
// #33 audit: imported frontmatter rides
|
||||
// verbatim, so the read-back gates on the same
|
||||
// format guard the decode applies — a hostile
|
||||
// value never pre-arms the publish sheet.
|
||||
micropubURL: frontmatter["micropub_url"].flatMap {
|
||||
Micropub.trustworthyURL($0) ? $0 : nil
|
||||
},
|
||||
// #32 read-back gate: the capture gate's immutable
|
||||
// pair (origin writer, type post) — NOT pass_state,
|
||||
// which legitimately advances after the capture.
|
||||
// `stats_*` keys can arrive by import (external YAML
|
||||
// rides verbatim), so an imported ai piece or outline
|
||||
// carrying hand-stamped keys still never renders;
|
||||
// a migrated writer piece keeps its real arc.
|
||||
firstDraftStats: origin == .writer && type == .post
|
||||
? Post.FirstDraftStats(frontmatter: frontmatter) : nil,
|
||||
),
|
||||
// #143: unchanged post.md (path + mtime + size) → reuse
|
||||
// the prior parse. The walk stays the truth; only the
|
||||
// read is skipped. One stamp serves consult AND store —
|
||||
// taken before both, so a mid-scan rewrite can never be
|
||||
// pinned as fresh (see store).
|
||||
let stamp = PostScanCache.stamp(at: fileURL)
|
||||
if let cached = cache?.cachedPost(at: fileURL, stamp: stamp) {
|
||||
guard seen.insert(dir.lastPathComponent).inserted else { continue }
|
||||
posts.append(cached)
|
||||
continue
|
||||
}
|
||||
guard let text = try? String(contentsOf: fileURL, encoding: .utf8),
|
||||
seen.insert(dir.lastPathComponent).inserted else { continue }
|
||||
let post = parse(
|
||||
text: text,
|
||||
id: dir.lastPathComponent,
|
||||
project: projectDir.lastPathComponent,
|
||||
isArchived: isArchived,
|
||||
)
|
||||
cache?.store(post, at: fileURL, stamp: stamp)
|
||||
posts.append(post)
|
||||
}
|
||||
}
|
||||
}
|
||||
return posts.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
|
||||
}
|
||||
|
||||
/// One post.md's text parsed into a Post — the scan's miss path (#143
|
||||
/// kept this a pure function of (text, location); the cache memoizes
|
||||
/// its output, nothing else).
|
||||
private static func parse(text: String, id: String, project: String, isArchived: Bool) -> Post {
|
||||
let frontmatter = frontmatter(of: text)
|
||||
let origin = Origin(rawValue: frontmatter["origin"] ?? "") ?? .writer
|
||||
let type = ContentType(rawValue: frontmatter["type"] ?? "") ?? .post
|
||||
return Post(
|
||||
id: id,
|
||||
title: title(of: text),
|
||||
passState: PassState(rawValue: frontmatter["pass_state"] ?? "") ?? .firstDraft,
|
||||
origin: origin,
|
||||
type: type,
|
||||
project: project,
|
||||
isArchived: isArchived,
|
||||
// #33: the remembered Micro.blog draft URL —
|
||||
// one flat key, read leniently like the rest.
|
||||
// #33 audit: imported frontmatter rides
|
||||
// verbatim, so the read-back gates on the same
|
||||
// format guard the decode applies — a hostile
|
||||
// value never pre-arms the publish sheet.
|
||||
micropubURL: frontmatter["micropub_url"].flatMap {
|
||||
Micropub.trustworthyURL($0) ? $0 : nil
|
||||
},
|
||||
// #32 read-back gate: the capture gate's immutable
|
||||
// pair (origin writer, type post) — NOT pass_state,
|
||||
// which legitimately advances after the capture.
|
||||
// `stats_*` keys can arrive by import (external YAML
|
||||
// rides verbatim), so an imported ai piece or outline
|
||||
// carrying hand-stamped keys still never renders;
|
||||
// a migrated writer piece keeps its real arc.
|
||||
firstDraftStats: origin == .writer && type == .post
|
||||
? Post.FirstDraftStats(frontmatter: frontmatter) : nil,
|
||||
)
|
||||
}
|
||||
|
||||
/// The `---`-delimited frontmatter block if present; empty otherwise.
|
||||
/// Quoted scalar values (`origin: "ai"`) are unquoted — lenient YAML.
|
||||
static func frontmatter(of text: String) -> [String: String] {
|
||||
@@ -224,6 +251,80 @@ nonisolated struct Post: Identifiable, Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
/// #143 (OPT-F3): parse memo for `Post.scan`. A post.md whose PATH,
|
||||
/// mtime, and size are unchanged since the last parse is not re-read —
|
||||
/// the prior `Post` is reused — so a watcher burst (the autosave echo)
|
||||
/// costs the readdir walk plus the changed files, not O(library bytes).
|
||||
/// Path-keyed: a moved piece always re-parses and re-derives its
|
||||
/// project/isArchived from disk. Held by `PostsModel` across rescans.
|
||||
///
|
||||
/// ponytail: mtime+size is the invalidation key (make/rsync class) — a
|
||||
/// same-size rewrite inside APFS timestamp granularity could serve a stale
|
||||
/// parse; key on a content hash if that ever bites. Entries for vanished
|
||||
/// paths are never consulted again and merely linger (bytes each).
|
||||
///
|
||||
final nonisolated class PostScanCache: @unchecked Sendable {
|
||||
private struct Entry {
|
||||
let modified: Date
|
||||
let size: Int
|
||||
let post: Post
|
||||
}
|
||||
|
||||
private var entries: [String: Entry] = [:]
|
||||
private let lock = NSLock()
|
||||
/// Hit/miss observables (a miss = one disk read + parse); test-facing.
|
||||
private var hitCount = 0
|
||||
private var missCount = 0
|
||||
|
||||
var hits: Int {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
return hitCount
|
||||
}
|
||||
|
||||
var misses: Int {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
return missCount
|
||||
}
|
||||
|
||||
/// The cached parse when (path, mtime, size) all match the caller's
|
||||
/// pre-captured stamp; nil = re-read. No I/O here — the stamp travels
|
||||
/// with the scan loop's consult and store alike.
|
||||
func cachedPost(at url: URL, stamp: Stamp) -> Post? {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
guard let entry = entries[url.path],
|
||||
stamp.modified == entry.modified,
|
||||
stamp.size == entry.size else { return nil }
|
||||
hitCount += 1
|
||||
return entry.post
|
||||
}
|
||||
|
||||
/// Remember a fresh parse under the caller's PRE-READ stamp; one store
|
||||
/// = one counted miss (disk read). Overlapping rescans can interleave:
|
||||
/// a store that stamped the file itself could key a pre-rewrite parse
|
||||
/// as the post-rewrite version and pin stale content until the next
|
||||
/// write. Keying the pre-read stamp instead makes a mid-flight rewrite
|
||||
/// mismatch on the next scan — a miss, self-healed.
|
||||
func store(_ post: Post, at url: URL, stamp: Stamp) {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
missCount += 1
|
||||
guard let modified = stamp.modified, let size = stamp.size else { return }
|
||||
entries[url.path] = Entry(modified: modified, size: size, post: post)
|
||||
}
|
||||
|
||||
/// A file's (mtime, size) at one moment — the invalidation key.
|
||||
struct Stamp {
|
||||
let modified: Date?
|
||||
let size: Int?
|
||||
}
|
||||
|
||||
/// Capture the stamp for a file (nils when it can't be read — the
|
||||
/// store then caches nothing, a conservative miss).
|
||||
static func stamp(at url: URL) -> Stamp {
|
||||
let values = try? url.resourceValues(forKeys: [.contentModificationDateKey, .fileSizeKey])
|
||||
return Stamp(modified: values?.contentModificationDate, size: values?.fileSize)
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension Substring {
|
||||
func trimmed() -> String {
|
||||
// whitespacesAndNewlines, not .whitespaces: a CRLF file's lines carry
|
||||
|
||||
Reference in new issue
Block a user