Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow closing the SFTP channel, and provide a with-style method as well #75

Merged
merged 1 commit into from
Nov 8, 2024
Merged
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
32 changes: 32 additions & 0 deletions Sources/Citadel/SFTP/Client/SFTPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ public final class SFTPClient: Sendable {
self.responses = responses
self.logger = logger
}

public func close() async throws {
try await self.channel.close()
}

fileprivate static func setupChannelHanders(channel: Channel, logger: Logger) -> EventLoopFuture<SFTPClient> {
let responses = SFTPResponses(sftpVersion: channel.eventLoop.makePromise())
Expand Down Expand Up @@ -287,6 +291,34 @@ public final class SFTPClient: Sendable {
}

extension SSHClient {
/// Open a SFTP subchannel over the SSH connection using the `sftp` subsystem.
///
/// - Parameters:
/// - logger: A logger to use for logging SFTP operations. Creates a new logger by default. See below for details.
/// - closure: A closure to execute with the opened SFTP client. The client is automatically closed when the
/// closure returns.
///
/// ## Logging levels
///
/// Several events in the lifetime of an SFTP connection are logged to the provided logger at various levels:
/// - `.critical`, `.error`: Unused.
/// - `.warning`: Logs non-`ok` SFTP status responses and SSH-level errors.
/// - `.info`: Logs major interesting events in the SFTP connection lifecycle (opened, closed, etc.)
/// - `.debug`: Logs detailed connection events (opened file, read from file, wrote to file, etc.)
/// - `.trace`: Logs a protocol-level packet trace, including raw packet bytes (excluding large items such
/// as incoming data read from a file). Care is taken to ensure sensitive information is not included in
/// packet traces.
public func withSFTP<ReturnType>(
logger: Logger = .init(label: "nl.orlandos.citadel.sftp"),
_ closure: @escaping @Sendable (SFTPClient) async throws -> ReturnType
) async throws -> ReturnType {
let client = try await self.openSFTP(logger: logger)
defer {
try? client.close()
}
return try await closure(client)
}

/// Open a SFTP subchannel over the SSH connection using the `sftp` subsystem.
///
/// - Parameters:
Expand Down
Loading