diff --git a/Package.swift b/Package.swift index ccd53ef..c8ce730 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .library(name: "HummingbirdPostgres", targets: ["HummingbirdPostgres"]), ], dependencies: [ - .package(url: "https://github.com/hummingbird-project/hummingbird.git", branch: "2.x.x"), + .package(url: "https://github.com/hummingbird-project/hummingbird.git", branch: "main"), .package(url: "https://github.com/vapor/postgres-nio", from: "1.20.0"), ], targets: [ diff --git a/Sources/HummingbirdJobsPostgres/Migrations/CreateJobQueue.swift b/Sources/HummingbirdJobsPostgres/Migrations/CreateJobQueue.swift index 6353981..1d9adb1 100644 --- a/Sources/HummingbirdJobsPostgres/Migrations/CreateJobQueue.swift +++ b/Sources/HummingbirdJobsPostgres/Migrations/CreateJobQueue.swift @@ -16,7 +16,7 @@ import HummingbirdPostgres import Logging @_spi(ConnectionPool) import PostgresNIO -struct CreateJobQueue: HBPostgresMigration { +struct CreateJobQueue: PostgresMigration { func apply(connection: PostgresConnection, logger: Logger) async throws { try await connection.query( """ @@ -44,5 +44,5 @@ struct CreateJobQueue: HBPostgresMigration { } var name: String { "_Create_JobQueue_Table_" } - var group: HBMigrationGroup { .jobQueue } + var group: MigrationGroup { .jobQueue } } diff --git a/Sources/HummingbirdJobsPostgres/Migrations/CreateJobs.swift b/Sources/HummingbirdJobsPostgres/Migrations/CreateJobs.swift index bad67e0..8d2c162 100644 --- a/Sources/HummingbirdJobsPostgres/Migrations/CreateJobs.swift +++ b/Sources/HummingbirdJobsPostgres/Migrations/CreateJobs.swift @@ -16,7 +16,7 @@ import HummingbirdPostgres import Logging @_spi(ConnectionPool) import PostgresNIO -struct CreateJobs: HBPostgresMigration { +struct CreateJobs: PostgresMigration { func apply(connection: PostgresConnection, logger: Logger) async throws { try await connection.query( """ @@ -39,10 +39,10 @@ struct CreateJobs: HBPostgresMigration { } var name: String { "_Create_Jobs_Table_" } - var group: HBMigrationGroup { .jobQueue } + var group: MigrationGroup { .jobQueue } } -extension HBMigrationGroup { +extension MigrationGroup { /// JobQueue migration group public static var jobQueue: Self { .init("_hb_jobqueue") } } diff --git a/Sources/HummingbirdJobsPostgres/PostgresJobsQueue.swift b/Sources/HummingbirdJobsPostgres/PostgresJobsQueue.swift index 88ddb26..a786b4f 100644 --- a/Sources/HummingbirdJobsPostgres/PostgresJobsQueue.swift +++ b/Sources/HummingbirdJobsPostgres/PostgresJobsQueue.swift @@ -21,7 +21,7 @@ import NIOCore @_spi(ConnectionPool) import PostgresNIO @_spi(ConnectionPool) -public final class HBPostgresQueue: HBJobQueueDriver { +public final class PostgresQueue: JobQueueDriver { public typealias JobID = UUID /// what to do with failed/processing jobs from last time queue was handled @@ -31,7 +31,7 @@ public final class HBPostgresQueue: HBJobQueueDriver { case remove } - /// Errors thrown by HBPostgresJobQueue + /// Errors thrown by PostgresJobQueue public enum PostgresQueueError: Error, CustomStringConvertible { case failedToAdd @@ -77,11 +77,11 @@ public final class HBPostgresQueue: HBJobQueueDriver { /// Logger used by queue public let logger: Logger - let migrations: HBPostgresMigrations + let migrations: PostgresMigrations let isStopped: NIOLockedValueBox - /// Initialize a HBPostgresJobQueue - public init(client: PostgresClient, migrations: HBPostgresMigrations, configuration: Configuration = .init(), logger: Logger) async { + /// Initialize a PostgresJobQueue + public init(client: PostgresClient, migrations: PostgresMigrations, configuration: Configuration = .init(), logger: Logger) async { self.client = client self.configuration = configuration self.logger = logger @@ -112,7 +112,7 @@ public final class HBPostgresQueue: HBJobQueueDriver { /// - Returns: Identifier of queued job @discardableResult public func push(_ buffer: ByteBuffer) async throws -> JobID { try await self.client.withConnection { connection in - let queuedJob = HBQueuedJob(id: .init(), jobBuffer: buffer) + let queuedJob = QueuedJob(id: .init(), jobBuffer: buffer) try await add(queuedJob, connection: connection) try await addToQueue(jobId: queuedJob.id, connection: connection) return queuedJob.id @@ -141,9 +141,9 @@ public final class HBPostgresQueue: HBJobQueueDriver { /// shutdown queue once all active jobs have been processed public func shutdownGracefully() async {} - func popFirst() async throws -> HBQueuedJob? { + func popFirst() async throws -> QueuedJob? { do { - return try await self.client.withConnection { connection -> HBQueuedJob? in + return try await self.client.withConnection { connection -> QueuedJob? in while true { try Task.checkCancellation() let stream = try await connection.query( @@ -176,7 +176,7 @@ public final class HBPostgresQueue: HBJobQueueDriver { guard let buffer = try await stream2.decode(ByteBuffer.self, context: .default).first(where: { _ in true }) else { continue } - return HBQueuedJob(id: jobId, jobBuffer: buffer) + return QueuedJob(id: jobId, jobBuffer: buffer) } catch { try await self.setStatus(jobId: jobId, status: .failed, connection: connection) throw JobQueueError.decodeJobFailed @@ -189,7 +189,7 @@ public final class HBPostgresQueue: HBJobQueueDriver { } } - func add(_ job: HBQueuedJob, connection: PostgresConnection) async throws { + func add(_ job: QueuedJob, connection: PostgresConnection) async throws { try await connection.query( """ INSERT INTO _hb_pg_jobs (id, job, status) @@ -256,10 +256,10 @@ public final class HBPostgresQueue: HBJobQueueDriver { } } -/// extend HBPostgresJobQueue to conform to AsyncSequence -extension HBPostgresQueue { +/// extend PostgresJobQueue to conform to AsyncSequence +extension PostgresQueue { public struct AsyncIterator: AsyncIteratorProtocol { - let queue: HBPostgresQueue + let queue: PostgresQueue public func next() async throws -> Element? { while true { @@ -281,13 +281,13 @@ extension HBPostgresQueue { } @_spi(ConnectionPool) -extension HBJobQueueDriver where Self == HBPostgresQueue { +extension JobQueueDriver where Self == PostgresQueue { /// Return Postgres driver for Job Queue /// - Parameters: /// - client: Postgres client /// - configuration: Queue configuration /// - logger: Logger used by queue - public static func postgres(client: PostgresClient, migrations: HBPostgresMigrations, configuration: HBPostgresQueue.Configuration = .init(), logger: Logger) async -> Self { + public static func postgres(client: PostgresClient, migrations: PostgresMigrations, configuration: PostgresQueue.Configuration = .init(), logger: Logger) async -> Self { await Self(client: client, migrations: migrations, configuration: configuration, logger: logger) } } diff --git a/Sources/HummingbirdPostgres/CreatePersistTable.swift b/Sources/HummingbirdPostgres/CreatePersistTable.swift index 576639c..eeb8ceb 100644 --- a/Sources/HummingbirdPostgres/CreatePersistTable.swift +++ b/Sources/HummingbirdPostgres/CreatePersistTable.swift @@ -15,7 +15,7 @@ import Logging @_spi(ConnectionPool) import PostgresNIO -struct CreatePersistTable: HBPostgresMigration { +struct CreatePersistTable: PostgresMigration { func apply(connection: PostgresConnection, logger: Logger) async throws { try await connection.query( """ @@ -37,10 +37,10 @@ struct CreatePersistTable: HBPostgresMigration { } var name: String { "_Create_Persist_Table_" } - var group: HBMigrationGroup { .persist } + var group: MigrationGroup { .persist } } -extension HBMigrationGroup { +extension MigrationGroup { /// Persist driver migration group public static var persist: Self { .init("_hb_pg_persist") } } diff --git a/Sources/HummingbirdPostgres/Migration.swift b/Sources/HummingbirdPostgres/Migration.swift index 77a9442..b2c9712 100644 --- a/Sources/HummingbirdPostgres/Migration.swift +++ b/Sources/HummingbirdPostgres/Migration.swift @@ -18,7 +18,7 @@ import Logging /// Protocol for a database migration /// /// Requires two functions one to apply the database migration and one to revert it. -public protocol HBPostgresMigration { +public protocol PostgresMigration { /// Apply database migration func apply(connection: PostgresConnection, logger: Logger) async throws /// Revert database migration @@ -26,35 +26,35 @@ public protocol HBPostgresMigration { /// Migration name var name: String { get } /// Group migration belongs to - var group: HBMigrationGroup { get } + var group: MigrationGroup { get } } -extension HBPostgresMigration { +extension PostgresMigration { /// Default implementaion of name public var name: String { String(describing: Self.self) } /// Default group is default - public var group: HBMigrationGroup { .default } + public var group: MigrationGroup { .default } } /// Group identifier for a group of migrations. /// /// Migrations in one group are treated independently of migrations in other groups. You can add a /// migration to a group and it will not affect any subsequent migrations not in that group. By default -/// all migrations belong to the ``HBMigrationGroup.default`` group. +/// all migrations belong to the ``MigrationGroup.default`` group. /// /// To add a migration to a separate group you first need to define the group by adding a static variable -/// to `HBMigrationGroup`. +/// to `MigrationGroup`. /// ``` -/// extension HBMigrationGroup { +/// extension MigrationGroup { /// public static var `myGroup`: Self { .init("myGroup") } /// } /// ``` -/// After that use to ``HBPostgresMigration.group`` set the group for a migration. +/// After that use to ``PostgresMigration.group`` set the group for a migration. /// /// Only use a group different from `.default` if you are certain that the database elements you are /// creating within that group will always be independent of everything else in the database. Groups /// are useful for libraries that use migrations to setup their database elements. -public struct HBMigrationGroup: Hashable, Equatable { +public struct MigrationGroup: Hashable, Equatable { let name: String public init(_ name: String) { diff --git a/Sources/HummingbirdPostgres/MigrationError.swift b/Sources/HummingbirdPostgres/MigrationError.swift index 4aac917..fc8ef0e 100644 --- a/Sources/HummingbirdPostgres/MigrationError.swift +++ b/Sources/HummingbirdPostgres/MigrationError.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// /// Error thrown by migration code -public struct HBPostgresMigrationError: Error, Equatable { +public struct PostgresMigrationError: Error, Equatable { enum _Internal { case requiresChanges case cannotRevertMigration @@ -28,6 +28,6 @@ public struct HBPostgresMigrationError: Error, Equatable { /// The database requires a migration before the application can run static var requiresChanges: Self { .init(.requiresChanges) } /// Cannot revert a migration as we do not have its details. Add it to the revert list using - /// HBPostgresMigrations.add(revert:) + /// PostgresMigrations.add(revert:) static var cannotRevertMigration: Self { .init(.cannotRevertMigration) } } diff --git a/Sources/HummingbirdPostgres/Migrations.swift b/Sources/HummingbirdPostgres/Migrations.swift index e177a17..65b7fcd 100644 --- a/Sources/HummingbirdPostgres/Migrations.swift +++ b/Sources/HummingbirdPostgres/Migrations.swift @@ -16,18 +16,18 @@ import Logging @_spi(ConnectionPool) import PostgresNIO /// Database migration support -public actor HBPostgresMigrations { +public actor PostgresMigrations { enum State { case waiting([CheckedContinuation]) case completed case failed(Error) } - var migrations: [HBPostgresMigration] - var reverts: [String: HBPostgresMigration] + var migrations: [PostgresMigration] + var reverts: [String: PostgresMigration] var state: State - /// Initialize a HBPostgresMigrations object + /// Initialize a PostgresMigrations object public init() { self.migrations = [] self.reverts = [:] @@ -36,13 +36,13 @@ public actor HBPostgresMigrations { /// Add migration to list of migrations to be be applied /// - Parameter migration: Migration to be applied - public func add(_ migration: HBPostgresMigration) { + public func add(_ migration: PostgresMigration) { self.migrations.append(migration) } /// Add migration to list of reverts, that can be applied /// - Parameter migration: Migration to be reverted if necessary - public func revert(_ migration: HBPostgresMigration) { + public func revert(_ migration: PostgresMigration) { self.reverts[migration.name] = migration } @@ -64,7 +64,7 @@ public actor HBPostgresMigrations { /// - logger: Logger to use /// - dryRun: Should migrations actually be applied, or should we just report what would be applied and reverted @_spi(ConnectionPool) - public func apply(client: PostgresClient, groups: [HBMigrationGroup] = [], logger: Logger, dryRun: Bool) async throws { + public func apply(client: PostgresClient, groups: [MigrationGroup] = [], logger: Logger, dryRun: Bool) async throws { try await self.migrate(client: client, migrations: self.migrations, groups: groups, logger: logger, completeMigrations: true, dryRun: dryRun) } @@ -74,14 +74,14 @@ public actor HBPostgresMigrations { /// - logger: Logger to use /// - dryRun: Should migrations actually be reverted, or should we just report what would be reverted @_spi(ConnectionPool) - public func revert(client: PostgresClient, groups: [HBMigrationGroup] = [], logger: Logger, dryRun: Bool) async throws { + public func revert(client: PostgresClient, groups: [MigrationGroup] = [], logger: Logger, dryRun: Bool) async throws { try await self.migrate(client: client, migrations: [], groups: groups, logger: logger, completeMigrations: false, dryRun: dryRun) } private func migrate( client: PostgresClient, - migrations: [HBPostgresMigration], - groups: [HBMigrationGroup], + migrations: [PostgresMigration], + groups: [MigrationGroup], logger: Logger, completeMigrations: Bool, dryRun: Bool @@ -92,7 +92,7 @@ public actor HBPostgresMigrations { case .waiting: break } - let repository = HBPostgresMigrationRepository(client: client) + let repository = PostgresMigrationRepository(client: client) do { _ = try await repository.withContext(logger: logger) { context in // setup migration repository (create table) @@ -121,7 +121,7 @@ public actor HBPostgresMigrations { // look for migration to revert in migration list and revert dictionary. NB we are looking in the migration // array belonging to the type, not the one supplied to the function guard let migration = self.migrations.first(where: { $0.name == migrationName }) ?? self.reverts[migrationName] else { - throw HBPostgresMigrationError.cannotRevertMigration + throw PostgresMigrationError.cannotRevertMigration } logger.info("Reverting \(migration.name) from group \(group.name) \(dryRun ? " (dry run)" : "")") if !dryRun { @@ -145,7 +145,7 @@ public actor HBPostgresMigrations { } // if changes are required guard requiresChanges == false else { - throw HBPostgresMigrationError.requiresChanges + throw PostgresMigrationError.requiresChanges } } } catch { @@ -202,7 +202,7 @@ public actor HBPostgresMigrations { } /// Create, remove and list migrations -struct HBPostgresMigrationRepository { +struct PostgresMigrationRepository { struct Context { let connection: PostgresConnection let logger: Logger @@ -220,26 +220,26 @@ struct HBPostgresMigrationRepository { try await self.createMigrationsTable(connection: context.connection, logger: context.logger) } - func add(_ migration: HBPostgresMigration, context: Context) async throws { + func add(_ migration: PostgresMigration, context: Context) async throws { try await context.connection.query( "INSERT INTO _hb_migrations (\"name\", \"group\") VALUES (\(migration.name), \(migration.group.name))", logger: context.logger ) } - func remove(_ migration: HBPostgresMigration, context: Context) async throws { + func remove(_ migration: PostgresMigration, context: Context) async throws { try await context.connection.query( "DELETE FROM _hb_migrations WHERE name = \(migration.name)", logger: context.logger ) } - func getAll(context: Context) async throws -> [(name: String, group: HBMigrationGroup)] { + func getAll(context: Context) async throws -> [(name: String, group: MigrationGroup)] { let stream = try await context.connection.query( "SELECT \"name\", \"group\" FROM _hb_migrations ORDER BY \"order\"", logger: context.logger ) - var result: [(String, HBMigrationGroup)] = [] + var result: [(String, MigrationGroup)] = [] for try await (name, group) in stream.decode((String, String).self, context: .default) { result.append((name, .init(group))) } diff --git a/Sources/HummingbirdPostgres/PostgresPersistDriver.swift b/Sources/HummingbirdPostgres/PostgresPersistDriver.swift index f379719..89e7c17 100644 --- a/Sources/HummingbirdPostgres/PostgresPersistDriver.swift +++ b/Sources/HummingbirdPostgres/PostgresPersistDriver.swift @@ -28,7 +28,7 @@ extension PSQLError { } /// Fluent driver for persist system for storing persistent cross request key/value pairs -public final class HBPostgresPersistDriver: HBPersistDriver { +public final class PostgresPersistDriver: PersistDriver { struct WrapperObject: PostgresCodable, Codable { let value: Value @@ -50,14 +50,14 @@ public final class HBPostgresPersistDriver: HBPersistDriver { let client: PostgresClient let logger: Logger let tidyUpFrequency: Duration - let migrations: HBPostgresMigrations + let migrations: PostgresMigrations - /// Initialize HBFluentPersistDriver + /// Initialize FluentPersistDriver /// - Parameters: /// - client: Postgres client /// - tidyUpFrequequency: How frequently cleanup expired database entries should occur @_spi(ConnectionPool) - public init(client: PostgresClient, migrations: HBPostgresMigrations, tidyUpFrequency: Duration = .seconds(600), logger: Logger) async { + public init(client: PostgresClient, migrations: PostgresMigrations, tidyUpFrequency: Duration = .seconds(600), logger: Logger) async { self.client = client self.logger = logger self.tidyUpFrequency = tidyUpFrequency @@ -76,7 +76,7 @@ public final class HBPostgresPersistDriver: HBPersistDriver { ) } catch let error as PSQLError { if error.serverError == .uniqueViolation { - throw HBPersistError.duplicate + throw PersistError.duplicate } else { throw error } @@ -138,7 +138,7 @@ public final class HBPostgresPersistDriver: HBPersistDriver { } /// Service protocol requirements -extension HBPostgresPersistDriver { +extension PostgresPersistDriver { public func run() async throws { self.logger.info("Waiting for persist driver migrations to complete") try await self.migrations.waitUntilCompleted() diff --git a/Tests/HummingbirdPostgresTests/JobsTests.swift b/Tests/HummingbirdPostgresTests/JobsTests.swift index 7b433d3..f145d10 100644 --- a/Tests/HummingbirdPostgresTests/JobsTests.swift +++ b/Tests/HummingbirdPostgresTests/JobsTests.swift @@ -39,9 +39,9 @@ final class JobsTests: XCTestCase { #endif } - static let env = HBEnvironment() + static let env = Environment() - func createJobQueue(numWorkers: Int, configuration: HBPostgresQueue.Configuration, function: String = #function) async throws -> HBJobQueue { + func createJobQueue(numWorkers: Int, configuration: PostgresQueue.Configuration, function: String = #function) async throws -> JobQueue { let logger = { var logger = Logger(label: function) logger.logLevel = .debug @@ -51,9 +51,9 @@ final class JobsTests: XCTestCase { configuration: getPostgresConfiguration(), backgroundLogger: logger ) - let postgresMigrations = HBPostgresMigrations() - return await HBJobQueue( - HBPostgresQueue( + let postgresMigrations = PostgresMigrations() + return await JobQueue( + PostgresQueue( client: postgresClient, migrations: postgresMigrations, configuration: configuration, @@ -69,9 +69,9 @@ final class JobsTests: XCTestCase { /// Creates test client, runs test function abd ensures everything is /// shutdown correctly @discardableResult public func testJobQueue( - jobQueue: HBJobQueue, + jobQueue: JobQueue, revertMigrations: Bool = false, - test: (HBJobQueue) async throws -> T + test: (JobQueue) async throws -> T ) async throws -> T { do { return try await withThrowingTaskGroup(of: Void.self) { group in @@ -117,10 +117,10 @@ final class JobsTests: XCTestCase { /// shutdown correctly @discardableResult public func testJobQueue( numWorkers: Int, - configuration: HBPostgresQueue.Configuration = .init(failedJobsInitialization: .remove, processingJobsInitialization: .remove), + configuration: PostgresQueue.Configuration = .init(failedJobsInitialization: .remove, processingJobsInitialization: .remove), revertMigrations: Bool = true, function: String = #function, - test: (HBJobQueue) async throws -> T + test: (JobQueue) async throws -> T ) async throws -> T { let jobQueue = try await self.createJobQueue(numWorkers: numWorkers, configuration: configuration, function: function) return try await self.testJobQueue(jobQueue: jobQueue, revertMigrations: revertMigrations, test: test) @@ -128,9 +128,9 @@ final class JobsTests: XCTestCase { func testBasic() async throws { let expectation = XCTestExpectation(description: "TestJob.execute was called", expectedFulfillmentCount: 10) - let jobIdentifer = HBJobIdentifier(#function) + let jobIdentifer = JobIdentifier(#function) try await self.testJobQueue(numWorkers: 1) { jobQueue in - jobQueue.registerJob(jobIdentifer) { parameters, context in + jobQueue.registerJob(id: jobIdentifer) { parameters, context in context.logger.info("Parameters=\(parameters)") try await Task.sleep(for: .milliseconds(Int.random(in: 10..<50))) expectation.fulfill() @@ -151,13 +151,13 @@ final class JobsTests: XCTestCase { } func testMultipleWorkers() async throws { - let jobIdentifer = HBJobIdentifier(#function) + let jobIdentifer = JobIdentifier(#function) let runningJobCounter = ManagedAtomic(0) let maxRunningJobCounter = ManagedAtomic(0) let expectation = XCTestExpectation(description: "TestJob.execute was called", expectedFulfillmentCount: 10) try await self.testJobQueue(numWorkers: 4) { jobQueue in - jobQueue.registerJob(jobIdentifer) { parameters, context in + jobQueue.registerJob(id: jobIdentifer) { parameters, context in let runningJobs = runningJobCounter.wrappingIncrementThenLoad(by: 1, ordering: .relaxed) if runningJobs > maxRunningJobCounter.load(ordering: .relaxed) { maxRunningJobCounter.store(runningJobs, ordering: .relaxed) @@ -187,11 +187,11 @@ final class JobsTests: XCTestCase { } func testErrorRetryCount() async throws { - let jobIdentifer = HBJobIdentifier(#function) + let jobIdentifer = JobIdentifier(#function) let expectation = XCTestExpectation(description: "TestJob.execute was called", expectedFulfillmentCount: 4) struct FailedError: Error {} try await self.testJobQueue(numWorkers: 1) { jobQueue in - jobQueue.registerJob(jobIdentifer, maxRetryCount: 3) { _, _ in + jobQueue.registerJob(id: jobIdentifer, maxRetryCount: 3) { _, _ in expectation.fulfill() throw FailedError() } @@ -213,9 +213,9 @@ final class JobsTests: XCTestCase { let message: String } let expectation = XCTestExpectation(description: "TestJob.execute was called") - let jobIdentifer = HBJobIdentifier(#function) + let jobIdentifer = JobIdentifier(#function) try await self.testJobQueue(numWorkers: 1) { jobQueue in - jobQueue.registerJob(jobIdentifer) { parameters, _ in + jobQueue.registerJob(id: jobIdentifer) { parameters, _ in XCTAssertEqual(parameters.id, 23) XCTAssertEqual(parameters.message, "Hello!") expectation.fulfill() @@ -228,11 +228,11 @@ final class JobsTests: XCTestCase { /// Test job is cancelled on shutdown func testShutdownJob() async throws { - let jobIdentifer = HBJobIdentifier(#function) + let jobIdentifer = JobIdentifier(#function) let expectation = XCTestExpectation(description: "TestJob.execute was called", expectedFulfillmentCount: 1) try await self.testJobQueue(numWorkers: 4) { jobQueue in - jobQueue.registerJob(jobIdentifer) { _, _ in + jobQueue.registerJob(id: jobIdentifer) { _, _ in expectation.fulfill() try await Task.sleep(for: .milliseconds(1000)) } @@ -250,12 +250,12 @@ final class JobsTests: XCTestCase { /// test job fails to decode but queue continues to process func testFailToDecode() async throws { let string: NIOLockedValueBox = .init("") - let jobIdentifer1 = HBJobIdentifier(#function) - let jobIdentifer2 = HBJobIdentifier(#function) + let jobIdentifer1 = JobIdentifier(#function) + let jobIdentifer2 = JobIdentifier(#function) let expectation = XCTestExpectation(description: "job was called", expectedFulfillmentCount: 1) try await self.testJobQueue(numWorkers: 4) { jobQueue in - jobQueue.registerJob(jobIdentifer2) { parameters, _ in + jobQueue.registerJob(id: jobIdentifer2) { parameters, _ in string.withLockedValue { $0 = parameters } expectation.fulfill() } @@ -272,12 +272,12 @@ final class JobsTests: XCTestCase { /// is then rerun on startup of new server func testRerunAtStartup() async throws { struct RetryError: Error {} - let jobIdentifer = HBJobIdentifier(#function) + let jobIdentifer = JobIdentifier(#function) let firstTime = ManagedAtomic(true) let finished = ManagedAtomic(false) let failedExpectation = XCTestExpectation(description: "TestJob failed", expectedFulfillmentCount: 1) let succeededExpectation = XCTestExpectation(description: "TestJob2 succeeded", expectedFulfillmentCount: 1) - let job = HBJobDefinition(id: jobIdentifer) { _, _ in + let job = JobDefinition(id: jobIdentifer) { _, _ in if firstTime.compareExchange(expected: true, desired: false, ordering: .relaxed).original { failedExpectation.fulfill() throw RetryError() @@ -308,14 +308,14 @@ final class JobsTests: XCTestCase { } func testMultipleJobQueueHandlers() async throws { - let jobIdentifer = HBJobIdentifier(#function) + let jobIdentifer = JobIdentifier(#function) let expectation = XCTestExpectation(description: "TestJob.execute was called", expectedFulfillmentCount: 200) let logger = { var logger = Logger(label: "testMultipleJobQueueHandlers") logger.logLevel = .debug return logger }() - let job = HBJobDefinition(id: jobIdentifer) { parameters, context in + let job = JobDefinition(id: jobIdentifer) { parameters, context in context.logger.info("Parameters=\(parameters)") try await Task.sleep(for: .milliseconds(Int.random(in: 10..<50))) expectation.fulfill() @@ -324,8 +324,8 @@ final class JobsTests: XCTestCase { configuration: getPostgresConfiguration(), backgroundLogger: logger ) - let postgresMigrations = HBPostgresMigrations() - let jobQueue = await HBJobQueue( + let postgresMigrations = PostgresMigrations() + let jobQueue = await JobQueue( .postgres( client: postgresClient, migrations: postgresMigrations, @@ -335,9 +335,9 @@ final class JobsTests: XCTestCase { numWorkers: 2, logger: logger ) - let postgresMigrations2 = HBPostgresMigrations() - let jobQueue2 = await HBJobQueue( - HBPostgresQueue( + let postgresMigrations2 = PostgresMigrations() + let jobQueue2 = await JobQueue( + PostgresQueue( client: postgresClient, migrations: postgresMigrations2, configuration: .init(failedJobsInitialization: .remove, processingJobsInitialization: .remove), diff --git a/Tests/HummingbirdPostgresTests/MigrationTests.swift b/Tests/HummingbirdPostgresTests/MigrationTests.swift index 9f7d31d..8e385b2 100644 --- a/Tests/HummingbirdPostgresTests/MigrationTests.swift +++ b/Tests/HummingbirdPostgresTests/MigrationTests.swift @@ -6,7 +6,7 @@ import XCTest final class MigrationTests: XCTestCase { /// Test migration used to verify order or apply and reverts - struct TestMigration: HBPostgresMigration { + struct TestMigration: PostgresMigration { class Order { var value: Int @@ -25,7 +25,7 @@ final class MigrationTests: XCTestCase { order: Order = Order(), applyOrder: Int? = nil, revertOrder: Int? = nil, - group: HBMigrationGroup = .default + group: MigrationGroup = .default ) { self.order = order self.name = name @@ -47,7 +47,7 @@ final class MigrationTests: XCTestCase { } let name: String - let group: HBMigrationGroup + let group: MigrationGroup let order: Order let expectedApply: Int? let expectedRevert: Int? @@ -59,9 +59,9 @@ final class MigrationTests: XCTestCase { func testMigrations( revert: Bool = true, - groups: [HBMigrationGroup] = [.default], - _ setup: (HBPostgresMigrations) async throws -> Void, - verify: (HBPostgresMigrations, PostgresClient) async throws -> Void + groups: [MigrationGroup] = [.default], + _ setup: (PostgresMigrations) async throws -> Void, + verify: (PostgresMigrations, PostgresClient) async throws -> Void ) async throws { let logger = { var logger = Logger(label: "MigrationTests") @@ -72,7 +72,7 @@ final class MigrationTests: XCTestCase { configuration: getPostgresConfiguration(), backgroundLogger: logger ) - let migrations = HBPostgresMigrations() + let migrations = PostgresMigrations() try await setup(migrations) do { try await withThrowingTaskGroup(of: Void.self) { group in @@ -93,8 +93,8 @@ final class MigrationTests: XCTestCase { } } - func getAll(client: PostgresClient, groups: [HBMigrationGroup] = [.default]) async throws -> [String] { - let repository = HBPostgresMigrationRepository(client: client) + func getAll(client: PostgresClient, groups: [MigrationGroup] = [.default]) async throws -> [String] { + let repository = PostgresMigrationRepository(client: client) return try await repository.withContext(logger: self.logger) { context in try await repository.getAll(context: context).compactMap { migration in if groups.first(where: { group in return group == migration.group }) != nil { @@ -219,7 +219,7 @@ final class MigrationTests: XCTestCase { try await migrations.apply(client: client, groups: [.default], logger: self.logger, dryRun: true) } XCTFail("Shouldn't get here") - } catch let error as HBPostgresMigrationError where error == .requiresChanges {} + } catch let error as PostgresMigrationError where error == .requiresChanges {} try await self.testMigrations(groups: [.default, .test]) { migrations in await migrations.add(TestMigration(name: "test1")) await migrations.add(TestMigration(name: "test2")) @@ -336,6 +336,6 @@ final class MigrationTests: XCTestCase { } } -extension HBMigrationGroup { +extension MigrationGroup { static var test: Self { .init("test") } } diff --git a/Tests/HummingbirdPostgresTests/PersistTests.swift b/Tests/HummingbirdPostgresTests/PersistTests.swift index 187e868..d734da8 100644 --- a/Tests/HummingbirdPostgresTests/PersistTests.swift +++ b/Tests/HummingbirdPostgresTests/PersistTests.swift @@ -21,9 +21,9 @@ import ServiceLifecycle import XCTest final class PersistTests: XCTestCase { - func createApplication(_ updateRouter: (HBRouter, HBPersistDriver) -> Void = { _, _ in }) async throws -> some HBApplicationProtocol { - struct PostgresErrorMiddleware: HBMiddlewareProtocol { - func handle(_ request: HBRequest, context: Context, next: (HBRequest, Context) async throws -> HBResponse) async throws -> HBResponse { + func createApplication(_ updateRouter: (Router, PersistDriver) -> Void = { _, _ in }) async throws -> some ApplicationProtocol { + struct PostgresErrorMiddleware: RouterMiddleware { + func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response { do { return try await next(request, context) } catch let error as PSQLError { @@ -43,9 +43,9 @@ final class PersistTests: XCTestCase { configuration: getPostgresConfiguration(), backgroundLogger: logger ) - let postgresMigrations = HBPostgresMigrations() - let persist = await HBPostgresPersistDriver(client: postgresClient, migrations: postgresMigrations, logger: logger) - let router = HBRouter() + let postgresMigrations = PostgresMigrations() + let persist = await PostgresPersistDriver(client: postgresClient, migrations: postgresMigrations, logger: logger) + let router = Router() router.middlewares.add(PostgresErrorMiddleware()) router.put("/persist/:tag") { request, context -> HTTPResponse.Status in let buffer = try await request.body.collect(upTo: .max) @@ -54,23 +54,23 @@ final class PersistTests: XCTestCase { return .ok } router.put("/persist/:tag/:time") { request, context -> HTTPResponse.Status in - guard let time = context.parameters.get("time", as: Int.self) else { throw HBHTTPError(.badRequest) } + guard let time = context.parameters.get("time", as: Int.self) else { throw HTTPError(.badRequest) } let buffer = try await request.body.collect(upTo: .max) let tag = try context.parameters.require("tag") try await persist.set(key: tag, value: String(buffer: buffer), expires: .seconds(time)) return .ok } router.get("/persist/:tag") { _, context -> String? in - guard let tag = context.parameters.get("tag", as: String.self) else { throw HBHTTPError(.badRequest) } + guard let tag = context.parameters.get("tag", as: String.self) else { throw HTTPError(.badRequest) } return try await persist.get(key: tag, as: String.self) } router.delete("/persist/:tag") { _, context -> HTTPResponse.Status in - guard let tag = context.parameters.get("tag", as: String.self) else { throw HBHTTPError(.badRequest) } + guard let tag = context.parameters.get("tag", as: String.self) else { throw HTTPError(.badRequest) } try await persist.remove(key: tag) return .noContent } updateRouter(router, persist) - var app = HBApplication(responder: router.buildResponder()) + var app = Application(responder: router.buildResponder()) app.addServices(PostgresClientService(client: postgresClient), persist) app.runBeforeServerStart { try await postgresMigrations.apply(client: postgresClient, groups: [.persist], logger: logger, dryRun: false) @@ -117,8 +117,8 @@ final class PersistTests: XCTestCase { let tag = try context.parameters.require("tag") do { try await persist.create(key: tag, value: String(buffer: buffer)) - } catch let error as HBPersistError where error == .duplicate { - throw HBHTTPError(.conflict) + } catch let error as PersistError where error == .duplicate { + throw HTTPError(.conflict) } return .ok } @@ -176,13 +176,13 @@ final class PersistTests: XCTestCase { } let app = try await self.createApplication { router, persist in router.put("/codable/:tag") { request, context -> HTTPResponse.Status in - guard let tag = context.parameters.get("tag") else { throw HBHTTPError(.badRequest) } + guard let tag = context.parameters.get("tag") else { throw HTTPError(.badRequest) } let buffer = try await request.body.collect(upTo: .max) try await persist.set(key: tag, value: TestCodable(buffer: String(buffer: buffer))) return .ok } router.get("/codable/:tag") { _, context -> String? in - guard let tag = context.parameters.get("tag") else { throw HBHTTPError(.badRequest) } + guard let tag = context.parameters.get("tag") else { throw HTTPError(.badRequest) } let value = try await persist.get(key: tag, as: TestCodable.self) return value?.buffer } diff --git a/Tests/HummingbirdPostgresTests/TestUtils.swift b/Tests/HummingbirdPostgresTests/TestUtils.swift index 2d3d151..ee803bb 100644 --- a/Tests/HummingbirdPostgresTests/TestUtils.swift +++ b/Tests/HummingbirdPostgresTests/TestUtils.swift @@ -14,7 +14,7 @@ struct PostgresClientService: Service { } func getPostgresConfiguration() async throws -> PostgresClient.Configuration { - let env = try await HBEnvironment.shared.merging(with: .dotEnv()) + let env = try await Environment.shared.merging(with: .dotEnv()) return .init( host: env.get("POSTGRES_HOSTNAME") ?? "localhost", port: env.get("POSTGRES_PORT", as: Int.self) ?? 5432,