Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apple/Configs/PluginKit.xcconfig
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// When to raise each, and how the build stamps them: .claude/rules/plugin-system.md, ABI.
TABLEPRO_PLUGINKIT_VERSION = 42
TABLEPRO_PLUGINKIT_VERSION = 43
TABLEPRO_PLUGINKIT_MINIMUM_VERSION = 19
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import Foundation

// Left to the kernel, Darwin sends the first keepalive after 7,200 s of idle, while an AWS Network Load Balancer drops
// an idle flow after 350 s. A session with no query timeout has no read timeout either, so a reply lost with the flow,
// or on a path that died, blocked the statement for hours, and Stop's KILL QUERY could not reach the blocked read.
// These keep the flow open and fail a dead peer about 90 s after the last traffic, the values the PostgreSQL plugin
// gives libpq. A slow statement on a live server still completes: its kernel answers the probes.
public enum MySQLSocketKeepalive {
public static let idleSeconds: Int32 = 60
public static let intervalSeconds: Int32 = 10
public static let probeCount: Int32 = 3

public static func enable(on socket: Int32) -> Bool {
set(socket, SOL_SOCKET, SO_KEEPALIVE, 1)
&& set(socket, IPPROTO_TCP, TCP_KEEPALIVE, idleSeconds)
&& set(socket, IPPROTO_TCP, TCP_KEEPINTVL, intervalSeconds)
&& set(socket, IPPROTO_TCP, TCP_KEEPCNT, probeCount)
}

private static func set(_ socket: Int32, _ level: Int32, _ name: Int32, _ value: Int32) -> Bool {
var value = value
return setsockopt(socket, level, name, &value, socklen_t(MemoryLayout<Int32>.size)) == 0
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,13 @@ public enum PostgreSQLCatalogTypeNames {
case 1_083: return "time"
case 1_114: return "timestamp"
case 1_184: return "timestamptz"
case 1_186: return "interval"
case 1_266: return "timetz"
// The names the catalog lookup gives them, so a fresh session's stream header reads a bit string as one.
case 1_560: return "bit"
case 1_561: return "bit[]"
case 1_562: return "varbit"
case 1_563: return "varbit[]"
case 1_700: return "numeric"
case 2_950: return "uuid"
case 3_802: return "jsonb"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ public final class SQLiteAuthorizerPolicy: @unchecked Sendable {
"table_info", "table_xinfo", "table_list", "index_info", "index_xinfo", "index_list",
"foreign_key_list", "foreign_key_check", "integrity_check", "quick_check", "function_list",
"pragma_list", "module_list", "collation_list", "database_list", "compile_options",
// FTS5 runs it on every read of its table.
"data_version",
]

static func decision(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,19 @@ public struct PullResult: Sendable {
public let changedRecords: [CKRecord]
public let deletedRecordIDs: [CKRecord.ID]
public let newToken: CKServerChangeToken?

public init(changedRecords: [CKRecord], deletedRecordIDs: [CKRecord.ID], newToken: CKServerChangeToken?) {
// Records the zone holds that the fetch could not read, so their absence from `changedRecords` proves nothing.
public let unreadRecordIDs: [CKRecord.ID]

public init(
changedRecords: [CKRecord],
deletedRecordIDs: [CKRecord.ID],
newToken: CKServerChangeToken?,
unreadRecordIDs: [CKRecord.ID] = []
) {
self.changedRecords = changedRecords
self.deletedRecordIDs = deletedRecordIDs
self.newToken = newToken
self.unreadRecordIDs = unreadRecordIDs
}
}

Expand Down Expand Up @@ -228,6 +236,7 @@ public actor CloudKitSyncEngine {
public func pull(since token: CKServerChangeToken?) async throws -> PullResult {
var changedRecords: [CKRecord] = []
var deletedRecordIDs: [CKRecord.ID] = []
var unreadRecordIDs: [CKRecord.ID] = []
var cursor = token

while true {
Expand All @@ -237,13 +246,15 @@ public actor CloudKitSyncEngine {

changedRecords.append(contentsOf: page.result.changedRecords)
deletedRecordIDs.append(contentsOf: page.result.deletedRecordIDs)
unreadRecordIDs.append(contentsOf: page.result.unreadRecordIDs)
cursor = page.result.newToken ?? cursor

guard page.moreComing, page.result.newToken != nil else {
return PullResult(
changedRecords: changedRecords,
deletedRecordIDs: deletedRecordIDs,
newToken: cursor
newToken: cursor,
unreadRecordIDs: unreadRecordIDs
)
}
}
Expand All @@ -266,14 +277,19 @@ public actor CloudKitSyncEngine {

var changedRecords: [CKRecord] = []
var deletedRecordIDs: [CKRecord.ID] = []
var unreadRecordIDs: [CKRecord.ID] = []
var newToken: CKServerChangeToken?
var moreComing = false
var zoneError: Error?

return try await withCheckedThrowingContinuation { continuation in
operation.recordWasChangedBlock = { _, result in
if case .success(let record) = result {
operation.recordWasChangedBlock = { recordID, result in
switch result {
case .success(let record):
changedRecords.append(record)
case .failure(let error):
Self.logger.warning("Record fetch error: \(error.localizedDescription)")
unreadRecordIDs.append(recordID)
}
}

Expand Down Expand Up @@ -310,7 +326,8 @@ public actor CloudKitSyncEngine {
result: PullResult(
changedRecords: changedRecords,
deletedRecordIDs: deletedRecordIDs,
newToken: newToken
newToken: newToken,
unreadRecordIDs: unreadRecordIDs
),
moreComing: moreComing
))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import Darwin
import Foundation
import TableProMySQLCore
import Testing

struct MySQLSocketKeepaliveTests {
@Test("A TCP socket probes a silent peer after 60 s idle, every 10 s, and gives up after 3")
func tcpSocketTakesTheValues() throws {
let socket = Darwin.socket(AF_INET, SOCK_STREAM, 0)
try #require(socket >= 0)
defer { close(socket) }

#expect(MySQLSocketKeepalive.enable(on: socket))
#expect(Self.intOption(socket, SOL_SOCKET, SO_KEEPALIVE) != 0)
#expect(Self.intOption(socket, IPPROTO_TCP, TCP_KEEPALIVE) == 60)
#expect(Self.intOption(socket, IPPROTO_TCP, TCP_KEEPINTVL) == 10)
#expect(Self.intOption(socket, IPPROTO_TCP, TCP_KEEPCNT) == 3)
}

@Test("A dead peer fails about 90 s after the last traffic")
func deadPeerBound() {
let seconds = MySQLSocketKeepalive.idleSeconds + MySQLSocketKeepalive.intervalSeconds * MySQLSocketKeepalive.probeCount
#expect(seconds == 90)
}

@Test("A socket that is not TCP reports that the keepalive could not be set")
func localSocketRefuses() throws {
let socket = Darwin.socket(AF_UNIX, SOCK_STREAM, 0)
try #require(socket >= 0)
defer { close(socket) }

#expect(!MySQLSocketKeepalive.enable(on: socket))
}

private static func intOption(_ socket: Int32, _ level: Int32, _ name: Int32) -> Int32 {
var value: Int32 = 0
var length = socklen_t(MemoryLayout<Int32>.size)
getsockopt(socket, level, name, &value, &length)
return value
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import Foundation
import TableProPluginKit
import Testing

struct PluginColumnOriginsTests {
private let origins: [PluginColumnOrigin?] = [PluginColumnOrigin(schema: "public", table: "users", column: "email"), nil]

@Test("A capped stream keeps the origins its header reported")
func boundedStreamKeepsHeaderOrigins() async throws {
var header = PluginStreamHeader(columns: ["e", "lower"], columnTypeNames: ["text", "text"])
header.columnOrigins = origins
let stream = AsyncThrowingStream<PluginStreamElement, Error> { continuation in
continuation.yield(.header(header))
continuation.yield(.rows([[.text("a"), .text("b")], [.text("c"), .text("d")]]))
continuation.finish()
}

let result = try await PluginBoundedStream.collect(stream, rowCap: 1, startedAt: Date())

#expect(result.columnOrigins == origins)
#expect(result.isTruncated)
}

@Test("Origins survive encoding, and a result without the key decodes with none")
func codableRoundTrip() throws {
var result = PluginQueryResult(
columns: ["e", "lower"],
columnTypeNames: ["text", "text"],
rows: [],
rowsAffected: 0,
timing: PluginQueryTiming(total: 0)
)
result.columnOrigins = origins

let decoded = try JSONDecoder().decode(PluginQueryResult.self, from: JSONEncoder().encode(result))
#expect(decoded.columnOrigins == origins)

let unreported = try JSONDecoder().decode(PluginQueryResult.self, from: JSONEncoder().encode(PluginQueryResult.empty))
#expect(unreported.columnOrigins == nil)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,12 @@ struct PostgreSQLCatalogTypeNamesTests {
1_009: "text[]",
3_807: "jsonb[]",
2_950: "uuid",
701: "double precision"
701: "double precision",
1_560: "bit",
1_561: "bit[]",
1_562: "varbit",
1_563: "varbit[]",
1_186: "interval"
]
for (oid, name) in expected {
#expect(PostgreSQLCatalogTypeNames.builtinTypeName(for: oid) == name, "oid \(oid)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ public final class SourceEditorHost {
SourceEditor.dismantleNSViewController(controller, coordinator: coordinator)
}

// A large document's edit reaches the binding on a delay; nil when nothing is waiting.
public func takePendingTextWriteback() -> String? {
guard let textView = controller.textView else { return nil }
return coordinator.textSync.takePendingWriteback(from: textView)
}

// A SwiftUI state write leads to an update pass that consumes the editor's change latch; without one the latch
// would swallow the next text the owner pushes.
private func stateDidChange(from old: SourceEditorState, to new: SourceEditorState) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,27 @@ final class TextBindingSync {

// A run or save reads the binding, which trails the editor by the debounce on a large document.
func flushPendingWriteback(from textView: TextView) {
guard let pending = writebackTask else { return }
pending.cancel()
writebackTask = nil
guard writebackTask != nil else { return }
let newText = endPendingWriteback(from: textView)
guard case .binding(let binding) = text else { return }
binding.wrappedValue = newText
}

// For an owner about to point the binding at another document, or to drop the editor: the debounced edit goes
// to the caller, and the edit latch is released so the next document's text is applied.
func takePendingWriteback(from textView: TextView) -> String? {
guard writebackTask != nil else { return nil }
let newText = endPendingWriteback(from: textView)
phase.consumePendingEditorChange()
return newText
}

private func endPendingWriteback(from textView: TextView) -> String {
writebackTask?.cancel()
writebackTask = nil
let newText = textView.string
lastSyncedText = newText
binding.wrappedValue = newText
return newText
}

/// Pushes an external binding change down into the text view. The editor's
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,43 @@ final class SourceEditorBindingSyncTests {
#expect(bound == "external")
}

@MainActor
@Test func test_takeHandsTheDebouncedEditOverAndLetsTheNextDocumentIn() {
var bound = ""
var setterCallCount = 0
let coordinator = makeCoordinator(get: { bound }, set: { bound = $0; setterCallCount += 1 })
let largeText = String(repeating: "a", count: 500_001)
controller.textView.setText(largeText)
coordinator.textViewDidChangeText(
Notification(name: TextView.textDidChangeNotification, object: controller.textView)
)
#expect(coordinator.phase.isEditorChangePending)

let taken = coordinator.textSync.takePendingWriteback(from: controller.textView)

#expect(taken == largeText)
#expect(setterCallCount == 0)
#expect(coordinator.textSync.writebackTask == nil)
#expect(!coordinator.phase.isEditorChangePending)

coordinator.textSync.applyRepresentableText("SELECT 2", controller: controller)
#expect(controller.textView.string == "SELECT 2")
}

@MainActor
@Test func test_takeWithoutAPendingWritebackKeepsTheEditLatch() {
var bound = ""
let coordinator = makeCoordinator(get: { bound }, set: { bound = $0 })
controller.textView.setText("small edit")
coordinator.textViewDidChangeText(
Notification(name: TextView.textDidChangeNotification, object: controller.textView)
)
#expect(bound == "small edit")

#expect(coordinator.textSync.takePendingWriteback(from: controller.textView) == nil)
#expect(coordinator.phase.isEditorChangePending)
}

@MainActor
@Test func test_syncSkipsStaleBindingSnapshotWhileEditIsInFlight() {
var bound = ""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,20 @@ public struct MCPPrincipalMetadata: Sendable, Equatable {
public let issuedAt: Date
public let expiresAt: Date?
public let isBridgeCredential: Bool
public let isClaudeAgentCredential: Bool

public init(label: String?, issuedAt: Date, expiresAt: Date?, isBridgeCredential: Bool = false) {
public init(
label: String?,
issuedAt: Date,
expiresAt: Date?,
isBridgeCredential: Bool = false,
isClaudeAgentCredential: Bool = false
) {
self.label = label
self.issuedAt = issuedAt
self.expiresAt = expiresAt
self.isBridgeCredential = isBridgeCredential
self.isClaudeAgentCredential = isClaudeAgentCredential
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,35 @@ import Foundation
/// ask to be the bridge and inherit every grant the bridge had earned.
public enum MCPGrantSubject: Sendable, Equatable {
case bridge
// The Claude Agent chat mints a token for every turn and deletes it after, the way the bridge rotates.
case claudeAgent
case token(UUID)

public init(tokenId: UUID, isBridgeCredential: Bool, isClaudeAgentCredential: Bool) {
if isBridgeCredential {
self = .bridge
} else if isClaudeAgentCredential {
self = .claudeAgent
} else {
self = .token(tokenId)
}
}

public var storageKey: String {
switch self {
case .bridge: return "bridge"
case .claudeAgent: return "claude-agent"
case .token(let id): return id.uuidString
}
}
}

public extension MCPPrincipal {
var grantSubject: MCPGrantSubject {
metadata.isBridgeCredential ? .bridge : .token(tokenId)
MCPGrantSubject(
tokenId: tokenId,
isBridgeCredential: metadata.isBridgeCredential,
isClaudeAgentCredential: metadata.isClaudeAgentCredential
)
}
}
Loading
Loading