diff --git a/Shared/Extensions/ArticleStringFormatter.swift b/Shared/Extensions/ArticleStringFormatter.swift index 9b830d99c..44b306368 100644 --- a/Shared/Extensions/ArticleStringFormatter.swift +++ b/Shared/Extensions/ArticleStringFormatter.swift @@ -12,11 +12,13 @@ import RSCore import RSParser @MainActor final class ArticleStringFormatter { + static let shared = ArticleStringFormatter() private var feedNameCache = [String: String]() - private var titleCache = [String: String]() - private var summaryCache = [String: String]() + private var titleCache = [TitleCacheKey: String]() + private var attributedTitleCache = [String: NSAttributedString]() + private var summaryCache = [ArticleCacheKey: String]() private let dateFormatter: DateFormatter = { let formatter = DateFormatter() @@ -37,70 +39,83 @@ import RSParser NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil) } - @objc func handleAppDidGoToBackground(_ notification: Notification) { - emptyCaches() - } - - @objc func handleLowMemory(_ notification: Notification) { - emptyCaches() - } - - private func emptyCaches() { - feedNameCache.removeAll() - titleCache.removeAll() - summaryCache.removeAll() - } - func truncatedFeedName(_ feedName: String) -> String { if let cachedFeedName = feedNameCache[feedName] { return cachedFeedName } let maxFeedNameLength = 100 - if feedName.count < maxFeedNameLength { + + // `utf8.count` is O(1); grapheme count <= utf8.count, so + // this is a conservative-but-correct short-enough check. + if feedName.utf8.count <= maxFeedNameLength { feedNameCache[feedName] = feedName return feedName } - let s = (feedName as NSString).substring(to: maxFeedNameLength) + // Grapheme-safe truncation, bounded by `maxFeedNameLength`. + let endIndex = feedName.index(feedName.startIndex, offsetBy: maxFeedNameLength, limitedBy: feedName.endIndex) ?? feedName.endIndex + let s = String(feedName[.. String { - guard let title = article.sanitizedTitle(forHTML: forHTML) else { + guard let rawTitle = article.title, !rawTitle.isEmpty else { return "" } - if let cachedTitle = titleCache[title] { + let cacheKey = TitleCacheKey(title: rawTitle, forHTML: forHTML) + if let cachedTitle = titleCache[cacheKey] { return cachedTitle } - var s = title.replacingOccurrences(of: "\n", with: "") - s = s.replacingOccurrences(of: "\r", with: "") - s = s.replacingOccurrences(of: "\t", with: "") + guard let sanitized = Self.sanitizedTitle(rawTitle, forHTML: forHTML) else { + return "" + } + + // Replace with " " rather than "" so words don't + // fuse (`"Part 1\nPart 2"` -> `"Part 1 Part 2"`). + // The `collapsingWhitespace` call further down removes any doubles. + var s = sanitized + if s.rangeOfCharacter(from: Self.titleControlCharacters) != nil { + s = s.replacingOccurrences(of: "\n", with: " ") + s = s.replacingOccurrences(of: "\r", with: " ") + s = s.replacingOccurrences(of: "\t", with: " ") + } if !forHTML { s = s.decodingHTMLEntities() } - s = s.trimmingWhitespace s = s.collapsingWhitespace let maxLength = 1000 - if s.count < maxLength { - titleCache[title] = s + + if s.utf8.count <= maxLength { + titleCache[cacheKey] = s return s } - s = (s as NSString).substring(to: maxLength) - titleCache[title] = s + // Grapheme-safe truncation. + let endIndex = s.index(s.startIndex, offsetBy: maxLength, limitedBy: s.endIndex) ?? s.endIndex + s = String(s[.. NSAttributedString { + guard let rawTitle = article.title, !rawTitle.isEmpty else { + return NSAttributedString() + } + + if let cached = attributedTitleCache[rawTitle] { + return cached + } + let title = truncatedTitle(article, forHTML: true) - let attributed = NSAttributedString(html: title) + let attributed = NSAttributedString(simpleHTML: title) + attributedTitleCache[rawTitle] = attributed return attributed } @@ -109,12 +124,18 @@ import RSParser return "" } - let key = article.articleID + article.accountID + let key = ArticleCacheKey(articleID: article.articleID, accountID: article.accountID) if let cachedBody = summaryCache[key] { return cachedBody } - var s = body.decodingHTMLEntities() - s = s.strippingHTML(maxCharacters: 300) + + // Strip first, then decode. Strip bounds the input to decode + // at ~300 characters regardless of body size, and it + // preserves author intent for entity-encoded tags like + // `<i>` (decode-then-strip would misread those as + // real `` tags and drop the text). + var s = body.strippingHTML(maxCharacters: 300) + s = s.decodingHTMLEntities() if s == "Comments" { // Hacker News. s = "" } @@ -122,6 +143,9 @@ import RSParser return s } + // `dateString` is intentionally uncached: ~97% of dates are + // unique at per-second precision in a real database, so a cache + // is a net regression vs calling DateFormatter directly. func dateString(_ date: Date) -> String { if Calendar.dateIsToday(date) { return timeFormatter.string(from: date) @@ -129,38 +153,18 @@ import RSParser return dateFormatter.string(from: date) } - // MARK: - Title sanitization - - // Stored as UTF-8 byte arrays so tag-name lookup during - // `sanitizedTitle` can be done byte-level without converting the - // scanned tag back to a String per call. - nonisolated private static let allowedTagsBytes: Set<[UInt8]> = { - let names = ["b", "bdi", "bdo", "cite", "code", "del", "dfn", "em", - "i", "ins", "kbd", "mark", "q", "s", "samp", "small", - "strong", "sub", "sup", "time", "u", "var"] - return Set(names.map { Array($0.utf8) }) - }() - - /// Sanitize an article title, which may contain HTML, into - /// either HTML-safe rendering (when `forHTML: true`) or a - /// plain-text form suitable for further processing (when - /// `forHTML: false`). Returns nil iff `title` is nil. + /// Sanitize an article title that may contain HTML. Returns nil + /// iff `title` is nil. /// - /// Behavior for each of the four (allowed, forHTML) combinations: - /// - allowed tag, forHTML=true: tag preserved as-is (`Bold`). + /// Behavior per (allowed, forHTML) combination: + /// - allowed tag, forHTML=true: tag preserved (`Bold`). /// - allowed tag, forHTML=false: tag dropped, contents kept. - /// - disallowed tag, forHTML=true: tag escaped as `<...>` text. - /// - disallowed tag, forHTML=false: tag preserved literally (the - /// caller — typically `strippingHTML` — removes it later). + /// - disallowed tag, forHTML=true: tag escaped as `<...>`. + /// - disallowed tag, forHTML=false: tag preserved literally + /// (a later `strippingHTML` pass removes it). /// - /// Implementation notes: single pass over UTF-8 bytes. `<`, `>`, - /// `/`, and ASCII tag characters are all single-byte; non-ASCII - /// bytes pass through as-is (correct for multi-byte text - /// content). The previous Scanner-based implementation went - /// through Foundation for every tag boundary, with per-tag - /// `scanUpToString` bridges and String allocations. On the cold - /// scroll path, that cost compounded across every unique article - /// title. + /// Single pass over UTF-8 bytes. Non-ASCII bytes pass through + /// unchanged — correct for multi-byte text content. nonisolated static func sanitizedTitle(_ title: String?, forHTML: Bool) -> String? { guard let title else { return nil @@ -177,8 +181,8 @@ import RSParser let lt = UInt8(ascii: "<") let gt = UInt8(ascii: ">") let slash = UInt8(ascii: "/") - // `<` and `>` as byte arrays — pre-encoded so the - // escape path doesn't pay a String-to-UTF8 conversion per tag. + // Pre-encoded `<` / `>` so the escape path doesn't + // convert String to UTF-8 per tag. let ltEntity: [UInt8] = [ UInt8(ascii: "&"), UInt8(ascii: "l"), UInt8(ascii: "t"), UInt8(ascii: ";") ] @@ -195,29 +199,22 @@ import RSParser continue } - // Found `<`. Scan forward for matching `>` or end of input. + // Scan forward for `>` or end of input. var j = i + 1 while j < count && utf8[j] != gt { j += 1 } - // Tag body is utf8[i+1..")` returns nil - // when no characters are scanned (either at end of - // string, or `>` is immediately next). In both cases we - // emit no tag and don't consume the `>` — the outer loop - // handles any trailing `>` as literal text on the next - // iteration. + // Empty tag body — emit nothing, skip the `<`, let the + // next iteration handle any trailing `>` as literal text. let tagStart = i + 1 let tagEnd = j if tagStart == tagEnd { - i += 1 // past the `<` only + i += 1 continue } - // Build a normalized tag name for lookup. The original - // used `tag.replacingOccurrences(of: "/", with: "")` — - // ALL slashes removed, case preserved. Match that. + // Normalize: strip ALL slashes, preserve case. var normalized = [UInt8]() normalized.reserveCapacity(tagEnd - tagStart) for k in tagStart..` if one was found, else to end of input. i = (j < count) ? j + 1 : count } return String(decoding: out, as: UTF8.self) } } + +// MARK: - Private + +private extension ArticleStringFormatter { + + // Article-identity key for the summary cache. Hashable struct + // avoids per-lookup String allocation. + struct ArticleCacheKey: Hashable { + let articleID: String + let accountID: String + } + + // (raw title, forHTML) key. Hit path skips `sanitizedTitle`. + // Including `forHTML` avoids a collision bug where tag-free + // titles sanitized identically but produced different output + // under the two flags. + struct TitleCacheKey: Hashable { + let title: String + let forHTML: Bool + } + + static let titleControlCharacters = CharacterSet(charactersIn: "\n\r\t") + + // UTF-8 byte arrays so tag-name lookup in `sanitizedTitle` stays + // byte-level — no String allocation per tag. + nonisolated static let allowedTagsBytes: Set<[UInt8]> = { + let names = ["b", "bdi", "bdo", "cite", "code", "del", "dfn", "em", + "i", "ins", "kbd", "mark", "q", "s", "samp", "small", + "strong", "sub", "sup", "time", "u", "var"] + return Set(names.map { Array($0.utf8) }) + }() + + @objc func handleAppDidGoToBackground(_ notification: Notification) { + emptyCaches() + } + + @objc func handleLowMemory(_ notification: Notification) { + emptyCaches() + } + + func emptyCaches() { + feedNameCache.removeAll() + titleCache.removeAll() + attributedTitleCache.removeAll() + summaryCache.removeAll() + } +} diff --git a/Tests/NetNewsWireTests/ArticleStringFormatterPerformanceTests.swift b/Tests/NetNewsWireTests/ArticleStringFormatterPerformanceTests.swift new file mode 100644 index 000000000..879355de3 --- /dev/null +++ b/Tests/NetNewsWireTests/ArticleStringFormatterPerformanceTests.swift @@ -0,0 +1,145 @@ +// +// ArticleStringFormatterPerformanceTests.swift +// NetNewsWireTests +// +// Created by Brent Simmons on 4/21/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Articles +import Foundation +import RSCore +import RSParser +import XCTest + +@testable import NetNewsWire + +/// Each test uses a fresh formatter per pass so every call hits the +/// code path (not the cache). +/// +/// Benchmark: release build, Apple Silicon — mean per-call time +/// captured at the point the legacy implementations were deleted: +/// +/// Function Legacy Current Speedup +/// ------------------------- ------------ ------------ ------- +/// truncatedFeedName 0.00000048 s 0.00000040 s ~1.2× +/// truncatedTitle 0.00000060 s 0.00000024 s ~2.5× +/// attributedTruncatedTitle 0.00000580 s 0.00000055 s ~11× +/// truncatedSummary 0.00001200 s 0.00000102 s ~12× +/// +@MainActor final class ArticleStringFormatterPerformanceTests: XCTestCase { + + private static let articles: [Article] = makePerformanceTestArticles() + private static let feedNames: [String] = makePerformanceTestFeedNames() + + func testTruncatedFeedName() { + measure { + for _ in 0..<1000 { + let formatter = ArticleStringFormatter() + for name in Self.feedNames { + _ = formatter.truncatedFeedName(name) + } + } + } + } + + func testTruncatedTitle() { + measure { + for _ in 0..<1000 { + let formatter = ArticleStringFormatter() + for article in Self.articles { + _ = formatter.truncatedTitle(article, forHTML: true) + _ = formatter.truncatedTitle(article, forHTML: false) + } + } + } + } + + func testAttributedTruncatedTitle() { + measure { + for _ in 0..<1000 { + let formatter = ArticleStringFormatter() + for article in Self.articles { + _ = formatter.attributedTruncatedTitle(article) + } + } + } + } + + func testTruncatedSummary() { + measure { + for _ in 0..<1000 { + let formatter = ArticleStringFormatter() + for article in Self.articles { + _ = formatter.truncatedSummary(article) + } + } + } + } +} + +// MARK: - Fixtures + +@MainActor private func makePerformanceTestArticles() -> [Article] { + let count = 100 + let sampleTitles = [ + "Simple plain title", + "Title with bold and italic and code", + "Title with entities & ampersand and "quotes" and <tags>", + "Long title with lots of words that stretches on and on for quite a while before ending", + "Unicode title with emoji 🎉 and accents café résumé", + "Title with\nnewlines\tand\ttabs" + ] + let entityParagraph = "

Tom & Jerry run a test — the body continues without any further entities for a good long while to exercise the post-ampersand slow path scanning across a realistic-scale article body.

" + let loremParagraph = "

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

" + let sampleBodies = [ + "

A short article body with no entities at all.

", + "

Paragraph with bold, italic, and links.

Second paragraph with & entities <tags> and more content.

", + String(repeating: entityParagraph, count: 100), + String(repeating: loremParagraph, count: 100), + "

Comments

" + ] + var result: [Article] = [] + result.reserveCapacity(count) + for i in 0.. [String] { + var names: [String] = [] + names.reserveCapacity(300) + for i in 0..<150 { + names.append("Feed \(i)") + } + let longPrefix = "An overly descriptive feed title with lots of padding text to ensure it exceeds the maximum limit for feed-name truncation testing purposes" + for i in 0..<100 { + names.append("\(longPrefix) part \(i)") + } + for i in 0..<50 { + names.append("Émojis 🎉🎊🎈 and accénts résumé café feed #\(i)") + } + return names +} diff --git a/Tests/NetNewsWireTests/ArticleStringFormatterTests.swift b/Tests/NetNewsWireTests/ArticleStringFormatterTests.swift new file mode 100644 index 000000000..633b9face --- /dev/null +++ b/Tests/NetNewsWireTests/ArticleStringFormatterTests.swift @@ -0,0 +1,238 @@ +// +// ArticleStringFormatterTests.swift +// NetNewsWireTests +// +// Created by Brent Simmons on 4/21/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Articles +import Foundation +import Testing + +@testable import NetNewsWire + +@MainActor @Suite struct ArticleStringFormatterTests { + + // MARK: - truncatedTitle + + @Test func truncatedTitlePlain() { + let article = makeArticle(title: "Hello World") + let formatter = ArticleStringFormatter() + #expect(formatter.truncatedTitle(article) == "Hello World") + } + + @Test("Control chars replace with spaces (so words don't fuse), then `collapsingWhitespace` squashes doubles") + func truncatedTitleReplacesControlCharactersWithSpaces() { + let article = makeArticle(title: "\rHello\nWorld\twith\r\t\rbreaks\n\t\r\r") + let formatter = ArticleStringFormatter() + #expect(formatter.truncatedTitle(article) == "Hello World with breaks") + } + + @Test func truncatedTitleDecodesEntitiesWhenNotForHTML() { + let article = makeArticle(title: "Tom & Jerry") + let formatter = ArticleStringFormatter() + #expect(formatter.truncatedTitle(article, forHTML: false) == "Tom & Jerry") + } + + @Test func truncatedTitleKeepsEntitiesWhenForHTML() { + let article = makeArticle(title: "Tom & Jerry") + let formatter = ArticleStringFormatter() + #expect(formatter.truncatedTitle(article, forHTML: true) == "Tom & Jerry") + } + + @Test func truncatedTitleEmptyForNilTitle() { + let article = makeArticle(title: nil) + let formatter = ArticleStringFormatter() + #expect(formatter.truncatedTitle(article) == "") + } + + @Test func truncatedTitleCachedResultIsStable() { + let article = makeArticle(title: "Repeated Title") + let formatter = ArticleStringFormatter() + let first = formatter.truncatedTitle(article) + let second = formatter.truncatedTitle(article) + #expect(first == second) + } + + // MARK: - forHTML collision regression + + // Regression test for a bug in the pre-optimization cache. + // + // Old behavior: the cache was keyed by the *sanitized* title. For an + // article whose title contained entities but no HTML tags (like + // "Tom & Jerry"), `sanitizedTitle(forHTML: true)` and + // `sanitizedTitle(forHTML: false)` produced the same sanitized + // string (the cache key) — but the two paths produce different + // *output* values: forHTML:false decodes `&` to `&`, forHTML:true + // preserves it. Whichever call happened first cached its variant and + // the other caller got the wrong string. + // + // New behavior: the cache key includes `forHTML`, so the two calls + // never collide. This test verifies the fix by calling both in the + // order that used to expose the bug. + @Test func forHTMLCollisionRegression() { + let article = makeArticle(title: "Tom & Jerry") + let formatter = ArticleStringFormatter() + + // Populate the plain-text cache first. + let plain = formatter.truncatedTitle(article, forHTML: false) + #expect(plain == "Tom & Jerry") + + // Now ask for the HTML version — must not return the cached + // plain-text result. + let html = formatter.truncatedTitle(article, forHTML: true) + #expect(html == "Tom & Jerry") + } + + @Test("Same as the collision test, but populating the HTML cache first") + func forHTMLCollisionRegressionReverseOrder() { + let article = makeArticle(title: "Tom & Jerry") + let formatter = ArticleStringFormatter() + + let html = formatter.truncatedTitle(article, forHTML: true) + #expect(html == "Tom & Jerry") + + let plain = formatter.truncatedTitle(article, forHTML: false) + #expect(plain == "Tom & Jerry") + } + + // MARK: - attributedTruncatedTitle + + @Test func attributedTruncatedTitleNonEmpty() { + let article = makeArticle(title: "Some Title") + let formatter = ArticleStringFormatter() + let attributed = formatter.attributedTruncatedTitle(article) + #expect(attributed.string == "Some Title") + } + + @Test func attributedTruncatedTitleEmptyForNilTitle() { + let article = makeArticle(title: nil) + let formatter = ArticleStringFormatter() + let attributed = formatter.attributedTruncatedTitle(article) + #expect(attributed.string == "") + } + + @Test("Warm-cache hits must return the same instance — callers mutate only via mutableCopy()") + func attributedTruncatedTitleReturnsCachedInstance() { + let article = makeArticle(title: "Cached") + let formatter = ArticleStringFormatter() + let first = formatter.attributedTruncatedTitle(article) + let second = formatter.attributedTruncatedTitle(article) + #expect(first === second) + } + + // MARK: - truncatedSummary + + @Test func truncatedSummaryFromContentHTML() { + let article = makeArticle(title: "T", contentHTML: "

Hello World

") + let formatter = ArticleStringFormatter() + #expect(formatter.truncatedSummary(article) == "Hello World") + } + + @Test func truncatedSummaryEmptyForNoBody() { + let article = makeArticle(title: "T", contentHTML: nil) + let formatter = ArticleStringFormatter() + #expect(formatter.truncatedSummary(article) == "") + } + + @Test("Strip output of \"Comments\" is special-cased to empty for Hacker News") + func truncatedSummaryHackerNewsCommentsBecomesEmpty() { + let article = makeArticle(title: "T", contentHTML: "Comments") + let formatter = ArticleStringFormatter() + #expect(formatter.truncatedSummary(article) == "") + } + + // Regression test for the decode/strip order swap. + // + // When an HTML author writes `<i>` in their article body, + // they mean the *literal text* "" should appear in the + // rendered output — not a real italic tag. The previous + // decode-then-strip order would decode `<i>` to `` and + // then strip it as if it were a tag, making the content + // disappear. The new strip-then-decode order preserves author + // intent. + @Test func summarySemanticsForEntityEncodedLiteralTags() { + let article = makeArticle( + title: "T", + contentHTML: "

Use <i> for italics.

" + ) + let formatter = ArticleStringFormatter() + #expect(formatter.truncatedSummary(article) == "Use for italics.") + } + + @Test("Real HTML tags and standalone entities — both old and new orders produce the same output here") + func summarySemanticsForTypicalHTML() { + let article = makeArticle( + title: "T", + contentHTML: "

Tom & Jerry

" + ) + let formatter = ArticleStringFormatter() + #expect(formatter.truncatedSummary(article) == "Tom & Jerry") + } + + // MARK: - dateString + + // `dateString` is intentionally uncached — a real-DB analysis + // showed 97% of dates are unique at per-second precision, making + // a cache a net regression. Just verify it returns a non-empty + // result and picks the time-format branch for today's dates. + @Test func dateStringTodayReturnsTimeString() { + let formatter = ArticleStringFormatter() + let now = Date() + let result = formatter.dateString(now) + #expect(!result.isEmpty) + // Time string won't contain the year; date string would. + let year = String(Calendar.current.component(.year, from: now)) + #expect(!result.contains(year)) + } + + @Test("Locale-independent smoke test: past date formats through the `.medium` date formatter") + func dateStringPastReturnsNonEmpty() { + let formatter = ArticleStringFormatter() + let longAgo = Date(timeIntervalSince1970: 0) // 1970-01-01 + #expect(!formatter.dateString(longAgo).isEmpty) + } + + // MARK: - truncatedFeedName + + @Test func truncatedFeedNameShortPassesThrough() { + let formatter = ArticleStringFormatter() + #expect(formatter.truncatedFeedName("Daring Fireball") == "Daring Fireball") + } + + @Test func truncatedFeedNameLongIsTruncated() { + let formatter = ArticleStringFormatter() + let feedName = String(repeating: "x", count: 200) + #expect(formatter.truncatedFeedName(feedName).count == 100) + } +} + +// MARK: - Helpers + +@MainActor private func makeArticle( + articleID: String = "article1", + accountID: String = "account1", + title: String? = "Untitled", + contentHTML: String? = nil +) -> Article { + let status = ArticleStatus(articleID: articleID, read: false, starred: false, dateArrived: Date()) + return Article( + accountID: accountID, + articleID: articleID, + feedID: "feed1", + uniqueID: "unique-\(articleID)", + title: title, + contentHTML: contentHTML, + contentText: nil, + markdown: nil, + url: nil, + externalURL: nil, + summary: nil, + imageURL: nil, + datePublished: Date(), + dateModified: nil, + authors: nil, + status: status + ) +}