Skip to content
Merged
14 changes: 14 additions & 0 deletions apple/Packages/TableProCore/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ let package = Package(
.library(name: "TableProKafkaCore", targets: ["TableProKafkaCore"]),
.library(name: "TableProCassandraCore", targets: ["TableProCassandraCore"]),
.library(name: "TableProEtcdCore", targets: ["TableProEtcdCore"]),
.library(name: "TableProElasticsearchCore", targets: ["TableProElasticsearchCore"]),
.library(name: "TableProDuckDBCore", targets: ["TableProDuckDBCore"])
],
// Kafka brokers hand back whatever codec the producer stored, and macOS has no zstd.
Expand Down Expand Up @@ -341,6 +342,13 @@ let package = Package(
path: "Sources/TableProPostgreSQLCore",
swiftSettings: pluginCoreSettings
),
// Linked by a plugin bundle, so never TableProPluginKit.
.target(
name: "TableProElasticsearchCore",
dependencies: [],
path: "Sources/TableProElasticsearchCore",
swiftSettings: pluginCoreSettings
),
.target(
name: "TableProMemcachedCore",
dependencies: [],
Expand Down Expand Up @@ -659,6 +667,12 @@ let package = Package(
path: "Tests/TableProCassandraCoreTests",
swiftSettings: pluginCoreSettings
),
.testTarget(
name: "TableProElasticsearchCoreTests",
dependencies: ["TableProElasticsearchCore"],
path: "Tests/TableProElasticsearchCoreTests",
swiftSettings: pluginCoreSettings
),
.testTarget(
name: "TableProEtcdCoreTests",
dependencies: ["TableProEtcdCore"],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// A page past max_result_window has no offset to jump to, so every hit before it is walked with search_after.
public struct ElasticsearchDeepPageWalk<Hit> {
public private(set) var page: [Hit] = []
public private(set) var isFinished: Bool
private var hitsLeftToSkip: Int
private let size: Int
private let batchSize: Int

public init(from: Int, size: Int, batchSize: Int) {
hitsLeftToSkip = max(0, from)
self.size = size
self.batchSize = batchSize
isFinished = size <= 0
}

// A batch that ends before the page starts is read for its sort values alone.
public var nextBatchNeedsDocuments: Bool { hitsLeftToSkip < batchSize }

public mutating func absorb(_ hits: [Hit]) {
let skipped = min(hitsLeftToSkip, hits.count)
hitsLeftToSkip -= skipped
page.append(contentsOf: hits.dropFirst(skipped).prefix(size - page.count))
if page.count >= size || hits.count < batchSize { isFinished = true }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ public struct MemcachedKeyEntry: Equatable, Sendable {
/// Unix time the item expires at, or nil for an item that never expires.
public let expiresAt: Int64?
public let flags: UInt32?
/// The bytes the listing reports for the item, or nil when it reports none.
public let size: Int?

public init(key: String, expiresAt: Int64?, flags: UInt32?) {
public init(key: String, expiresAt: Int64?, flags: UInt32?, size: Int? = nil) {
self.key = key
self.expiresAt = expiresAt
self.flags = flags
self.size = size
}

// Nil for no expiry, and for a clock too far from the expiry to subtract, so the item stays listed.
Expand Down Expand Up @@ -60,7 +63,8 @@ public enum MemcachedKeyListing {
return MemcachedKeyEntry(
key: key,
expiresAt: expiry.flatMap { $0 > 0 ? $0 : nil },
flags: fields["flags"].flatMap { UInt32($0) }
flags: fields["flags"].flatMap { UInt32($0) },
size: fields["size"].flatMap { Int($0) }
)
}

Expand All @@ -71,7 +75,12 @@ public enum MemcachedKeyListing {
guard !key.isEmpty else { return nil }
let inside = line[line.index(after: open)...].split(whereSeparator: { $0 == ";" || $0 == " " || $0 == "]" })
let expiry = inside.count >= 3 ? Int64(inside[2]) : nil
return MemcachedKeyEntry(key: key, expiresAt: expiry.flatMap { $0 > 0 ? $0 : nil }, flags: nil)
return MemcachedKeyEntry(
key: key,
expiresAt: expiry.flatMap { $0 > 0 ? $0 : nil },
flags: nil,
size: inside.first.flatMap { Int($0) }
)
}

public static func slabClasses(fromItemStats lines: [String]) -> [Int] {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
public enum MemcachedValueBatches {
static let maximumKeys = 1_000
// Proxies buffer a request line whole, so a page of long keys goes out as several shorter lines.
static let maximumLineBytes = 64 * 1_024
// A request's timeout covers its whole reply, so a page of large items is read in parts.
static let maximumListedBytes = 16 * 1_024 * 1_024

private static let commandOverhead = "gets \r\n".utf8.count

/// The keys of each `gets`, in listing order. A key over a limit by itself still goes out, alone.
public static func split(_ entries: some Collection<MemcachedKeyEntry>) -> [[String]] {
var batches: [[String]] = []
var keys: [String] = []
var lineBytes = commandOverhead
var listedBytes = 0

for entry in entries {
let keyBytes = entry.key.utf8.count + 1
// A listing is the server's word, so one absurd size cannot overflow the sum.
let itemBytes = min(max(entry.size ?? 0, 0), MemcachedReplyReader.maximumValueLength)
let isFull = keys.count >= maximumKeys
|| lineBytes + keyBytes > maximumLineBytes
|| listedBytes + itemBytes > maximumListedBytes
if isFull, !keys.isEmpty {
batches.append(keys)
keys = []
lineBytes = commandOverhead
listedBytes = 0
}
keys.append(entry.key)
lineBytes += keyBytes
listedBytes += itemBytes
}
if !keys.isEmpty { batches.append(keys) }
return batches
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import TableProElasticsearchCore
import Testing

private struct WalkOutcome {
let page: [Int]
let batchesWithDocuments: [Bool]
}

// An index of `total` hits, read the way the driver reads it. A hit read without documents is -1,
// so a page that kept one shows it.
private func walk(total: Int, from: Int, size: Int, batchSize: Int) -> WalkOutcome {
var walk = ElasticsearchDeepPageWalk<Int>(from: from, size: size, batchSize: batchSize)
var position = 0
var batches: [Bool] = []
while !walk.isFinished {
let withDocuments = walk.nextBatchNeedsDocuments
batches.append(withDocuments)
let end = min(position + batchSize, total)
walk.absorb((position ..< end).map { withDocuments ? $0 : -1 })
position = end
}
return WalkOutcome(page: walk.page, batchesWithDocuments: batches)
}

struct ElasticsearchDeepPageWalkTests {
@Test("Batches wholly before the page are read without documents")
func skippedBatchesCarryNoDocuments() {
let outcome = walk(total: 200_000, from: 100_000, size: 1_000, batchSize: 1_000)
#expect(outcome.batchesWithDocuments == Array(repeating: false, count: 100) + [true])
#expect(outcome.page == Array(100_000 ..< 101_000))
}

@Test("A batch the page starts inside is read with documents")
func batchHoldingThePageStartCarriesDocuments() {
let outcome = walk(total: 5_000, from: 1_500, size: 1_000, batchSize: 1_000)
#expect(outcome.batchesWithDocuments == [false, true, true])
#expect(outcome.page == Array(1_500 ..< 2_500))
}

@Test("A page starting on the last hit of a batch still reads that batch with documents")
func pageStartingOnTheLastHitOfABatch() {
let outcome = walk(total: 5_000, from: 999, size: 2, batchSize: 1_000)
#expect(outcome.batchesWithDocuments == [true, true])
#expect(outcome.page == [999, 1_000])
}

@Test("A page starting right after a batch skips that whole batch")
func pageStartingOnABatchBoundary() {
let outcome = walk(total: 5_000, from: 1_000, size: 2, batchSize: 1_000)
#expect(outcome.batchesWithDocuments == [false, true])
#expect(outcome.page == [1_000, 1_001])
}

@Test("An index that ends before the page gives an empty page")
func indexEndingBeforeThePage() {
let outcome = walk(total: 1_500, from: 100_000, size: 1_000, batchSize: 1_000)
#expect(outcome.page.isEmpty)
#expect(outcome.batchesWithDocuments.count == 2)
}

@Test("An index that ends inside the page gives the hits it has")
func indexEndingInsideThePage() {
let outcome = walk(total: 10_500, from: 10_000, size: 1_000, batchSize: 1_000)
#expect(outcome.page == Array(10_000 ..< 10_500))
}

@Test("A page of no rows reads nothing")
func emptyPageReadsNothing() {
let outcome = walk(total: 5_000, from: 10_000, size: 0, batchSize: 1_000)
#expect(outcome.batchesWithDocuments.isEmpty)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ struct MemcachedKeyListingTests {
let entry = MemcachedKeyListing.metadumpEntry(
"key=a%3A1 exp=1793500167 la=1793499867 cas=2 fetch=yes cls=1 size=71 flags=5 "
)
#expect(entry == MemcachedKeyEntry(key: "a:1", expiresAt: 1_793_500_167, flags: 5))
#expect(entry == MemcachedKeyEntry(key: "a:1", expiresAt: 1_793_500_167, flags: 5, size: 71))
#expect(entry?.secondsLeft(at: 1_793_499_867) == 300)
}

Expand All @@ -23,17 +23,17 @@ struct MemcachedKeyListingTests {
@Test("exp=-1 means the item never expires")
func metadumpNeverExpires() {
let entry = MemcachedKeyListing.metadumpEntry("key=%22sp%22 exp=-1 la=1 cas=4 fetch=no cls=1 size=64 flags=0")
#expect(entry == MemcachedKeyEntry(key: "\"sp\"", expiresAt: nil, flags: 0))
#expect(entry == MemcachedKeyEntry(key: "\"sp\"", expiresAt: nil, flags: 0, size: 64))
#expect(entry?.isExpired(at: .max) == false)
}

@Test("A cachedump line gives the key and expiry; 0 means never")
func cachedump() {
#expect(MemcachedKeyListing.cachedumpEntry("ITEM k1 [2 b; 0 s]") == MemcachedKeyEntry(
key: "k1", expiresAt: nil, flags: nil
key: "k1", expiresAt: nil, flags: nil, size: 2
))
#expect(MemcachedKeyListing.cachedumpEntry("ITEM user:42 [5 b; 1793500167 s]") == MemcachedKeyEntry(
key: "user:42", expiresAt: 1_793_500_167, flags: nil
key: "user:42", expiresAt: 1_793_500_167, flags: nil, size: 5
))
#expect(MemcachedKeyListing.cachedumpEntry("STAT pid 1") == nil)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import TableProMemcachedCore
import Testing

private func entries(_ count: Int, keyLength: Int = 12, size: Int? = 100) -> [MemcachedKeyEntry] {
(0 ..< count).map { index in
let suffix = String(index)
let padding = String(repeating: "k", count: max(0, keyLength - suffix.count))
return MemcachedKeyEntry(key: padding + suffix, expiresAt: nil, flags: nil, size: size)
}
}

struct MemcachedValueBatchesTests {
@Test("A page of 1,000 ordinary keys is read in one gets")
func pageIsOneRequest() {
#expect(MemcachedValueBatches.split(entries(1_000)).count == 1)
}

@Test("Key 1,001 starts a second gets")
func keyLimitStartsANewRequest() {
#expect(MemcachedValueBatches.split(entries(1_001)).map(\.count) == [1_000, 1])
}

@Test("Every key is read once, in listing order")
func keysKeepTheirOrder() {
let listed = entries(2_500, keyLength: 200)
#expect(MemcachedValueBatches.split(listed).flatMap { $0 } == listed.map(\.key))
}

@Test("Long keys keep every request line within 64 KiB")
func longKeysSplitTheLine() throws {
let batches = MemcachedValueBatches.split(entries(1_000, keyLength: 250))
#expect(batches.count > 1)
for keys in batches {
let command = MemcachedCommand.get(keys: keys, withCAS: true)
#expect(command.wireBytes.count <= 64 * 1_024)
}
}

@Test("Large listed items spread over several requests")
func largeItemsSplitTheReply() {
let batches = MemcachedValueBatches.split(entries(1_000, size: 1_024 * 1_024))
#expect(batches.map(\.count) == Array(repeating: 16, count: 62) + [8])
}

@Test("An item over the byte limit by itself is still read")
func oversizedItemGoesAlone() {
let listed = entries(3, size: 32 * 1_024 * 1_024)
#expect(MemcachedValueBatches.split(listed).map(\.count) == [1, 1, 1])
}

@Test("Items the listing gives no size for count only as keys")
func unknownSizesDoNotSplit() {
#expect(MemcachedValueBatches.split(entries(1_000, size: nil)).count == 1)
}

@Test("A size no server could report does not overflow the sum")
func absurdSizeDoesNotTrap() {
let listed = entries(3, size: .max)
#expect(MemcachedValueBatches.split(listed).flatMap { $0 } == listed.map(\.key))
}

@Test("No keys, no requests")
func noKeysNoRequests() {
#expect(MemcachedValueBatches.split([MemcachedKeyEntry]()).isEmpty)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import Foundation
import os
import TableProDocumentPath
import TableProElasticsearchCore
import TableProPluginKit

extension ElasticsearchPluginDriver {
Expand Down Expand Up @@ -260,35 +261,27 @@ extension ElasticsearchPluginDriver {
conn: ElasticsearchConnection
) async throws -> [[String: Any]] {
var searchAfter: [Any]?
var skipped = 0
var collected: [[String: Any]] = []
var walk = ElasticsearchDeepPageWalk<[String: Any]>(
from: parsed.from, size: parsed.size, batchSize: Self.deepPageBatchSize
)

while collected.count < parsed.size {
while !walk.isFinished {
try Task.checkCancellation()
var body = ElasticsearchQueryBuilder.searchBody(
for: parsed, fields: fields, size: Self.deepPageBatchSize,
tiebreaker: true, searchAfter: searchAfter, supportsCaseInsensitive: supportsCaseInsensitiveSearch
)
body["pit"] = ["id": pit.id, "keep_alive": Self.pitKeepAlive]
body["track_total_hits"] = false
if !walk.nextBatchNeedsDocuments { body["_source"] = false }
let response = try await conn.search(index: nil, body: body)
pit.adopt(from: response)
let hits = extractHits(response)
guard !hits.isEmpty else { break }

for hit in hits {
if skipped < parsed.from {
skipped += 1
} else if collected.count < parsed.size {
collected.append(hit)
}
searchAfter = hit["sort"] as? [Any]
}

if hits.count < Self.deepPageBatchSize { break }
walk.absorb(hits)
searchAfter = hits.last?["sort"] as? [Any]
}

return collected
return walk.page
}

// MARK: - Write
Expand Down
Loading
Loading