使用Vapor 3创建和使用游标

Dav*_*gle 4 swift vapor swift-nio

这可能是一堆蠕虫,我会尽力描述这个问题.我们有一个长期运行的数据处理工作.我们的行动数据库会在夜间添加,并处理未完成的操作.处理夜间行动大约需要15分钟.在Vapor 2中,我们使用了大量的原始查询来创建PostgreSQL游标并循环遍历它直到它为空.

目前,我们通过命令行参数运行处理.将来我们希望它作为主服务器的一部分运行,以便在执行处理时检查进度.

func run(using context: CommandContext) throws -> Future<Void> {
    let table = "\"RecRegAction\""
    let cursorName = "\"action_cursor\""
    let chunkSize = 10_000


    return context.container.withNewConnection(to: .psql) { connection in
        return PostgreSQLDatabase.transactionExecute({ connection -> Future<Int> in

            return connection.simpleQuery("DECLARE \(cursorName) CURSOR FOR SELECT * FROM \(table)").map { result in
                var totalResults = 0
                var finished : Bool = false

                while !finished {
                    let results = try connection.raw("FETCH \(chunkSize) FROM \(cursorName)").all(decoding: RecRegAction.self).wait()
                    if results.count > 0 {
                        totalResults += results.count
                        print(totalResults)
                        // Obviously we do our processing here
                    }
                    else {
                        finished = true
                    }
                }

                return totalResults
            }
        }, on: connection)
    }.transform(to: ())
}
Run Code Online (Sandbox Code Playgroud)

现在这不起作用,因为我正在调用wait()并且我得到错误"Precondition failed:在EventLoop上不能调用wait()"这是公平的.我面临的一个问题是,我不知道你是如何在主要的事件循环中运行这样在后台线程上运行这样的东西.我知道BlockingIOThreadPool,但似乎仍然在同一个EventLoop上运行并仍然导致错误.虽然我能够通过越来越复杂的方式来实现这一目标,但我希望我找不到一个优雅的解决方案,也许对SwiftNIO和Fluent有更好了解的人可以提供帮助.

编辑:要明确,这个目标显然不是要总计数据库中的操作数.目标是使用游标同步处理每个操作.当我读到结果时,我会检测到操作中的更改,然后将它们的批次抛出到处理线程中.当所有线程都忙时,我不会再次从光标读取,直到它们完成.

这些行动很多,一次运行多达4500万.聚合承诺和递归似乎并不是一个好主意,当我尝试它时,只是为了它,服务器挂起.

这是一个处理密集型任务,可以在一个线程上运行数天,所以我不关心创建新线程.问题是我无法弄清楚如何在Command中使用wait()函数,因为我需要一个容器来创建数据库连接,而我唯一可以访问的是context.container对此调用wait()会导致以上错误.

TIA

Joh*_*iss 9

好的,如你所知,问题在于以下几点:

while ... {
    ...
    try connection.raw("...").all(decoding: RecRegAction.self).wait()
    ...
}
Run Code Online (Sandbox Code Playgroud)

你想等待一些结果,因此你使用while循环和.wait()所有中间结果.本质上,这是在事件循环中将异步代码转换为同步代码.这可能会导致死锁,并且肯定会阻止其他连接,这就是为什么SwiftNIO会尝试检测到并导致错误的原因.我不会详细说明为什么它会阻止其他连接,或者为什么这可能会导致这个答案陷入僵局.

让我们看看我们有什么选择来解决这个问题:

  1. 正如你所说,我们可以.wait()在另一个不是事件循环线程之一的线程上使用它.对于这个任何EventLoop线程都会这样做:DispatchQueue或者你可以使用BlockingIOThreadPool(它不会运行EventLoop)
  2. 我们可以将您的代码重写为异步

两种解决方案都可以工作,但(1)实际上是不可取的,因为您只需要等待结果就可以刻录整个(内核)线程.两者DispatchBlockingIOThreadPool有一个有限的线程数他们愿意产卵,所以如果你这样做往往不够,你可能会用完线程所以它会需要更长的时间.

因此,让我们看看如何在累积中间结果的同时多次调用异步函数.然后,如果我们累积了所有中间结果,则继续所有结果.

为了简化操作,让我们看看与您的功能非常相似的功能.我们假设这个函数就像你的代码一样提供

/// delivers partial results (integers) and `nil` if no further elements are available
func deliverPartialResult() -> EventLoopFuture<Int?> {
    ...
}
Run Code Online (Sandbox Code Playgroud)

我们现在想要的是一个新功能

func deliverFullResult() -> EventLoopFuture<[Int]>
Run Code Online (Sandbox Code Playgroud)

请注意deliverPartialResult每次返回一个整数并deliverFullResult传递一个整数数组(即所有整数).好的,那我们怎么写deliverFullResult 而不打电话deliverPartialResult().wait()

那这个呢:

func accumulateResults(eventLoop: EventLoop,
                       partialResultsSoFar: [Int],
                       getPartial: @escaping () -> EventLoopFuture<Int?>) -> EventLoopFuture<[Int]> {
    // let's run getPartial once
    return getPartial().then { partialResult in
        // we got a partial result, let's check what it is
        if let partialResult = partialResult {
            // another intermediate results, let's accumulate and call getPartial again
            return accumulateResults(eventLoop: eventLoop,
                                     partialResultsSoFar: partialResultsSoFar + [partialResult],
                                     getPartial: getPartial)
        } else {
            // we've got all the partial results, yay, let's fulfill the overall future
            return eventLoop.newSucceededFuture(result: partialResultsSoFar)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

鉴于accumulateResults,实施deliverFullResult不再困难:

func deliverFullResult() -> EventLoopFuture<[Int]> {
    return accumulateResults(eventLoop: myCurrentEventLoop,
                             partialResultsSoFar: [],
                             getPartial: deliverPartialResult)
}
Run Code Online (Sandbox Code Playgroud)

但让我们更多地了解一下accumulateResults:

  1. 它调用getPartial一次,然后调用它
  2. 检查我们是否有
    • 部分结果,在这种情况下,我们记住它与另一个partialResultsSoFar并返回到(1)
    • nil这意味着partialResultsSoFar我们得到的一切,我们回归到目前为止我们收集的所有新的未来

那已经是真的了.我们在这里做的是将同步循环转换为异步递归.

好的,我们查看了很多代码,但这与你的功能现在有什么关系?

信不信由你,但这实际上应该有效(未经测试):

accumulateResults(eventLoop: el, partialResultsSoFar: []) {
    connection.raw("FETCH \(chunkSize) FROM \(cursorName)")
              .all(decoding: RecRegAction.self)
              .map { results -> Int? in
        if results.count > 0 {
            return results.count
        } else {
            return nil
        }
   }
}.map { allResults in
    return allResults.reduce(0, +)
}
Run Code Online (Sandbox Code Playgroud)

所有这一切的结果将是一个EventLoopFuture<Int>携带所有中间人的总和result.count.

当然,我们首先将你的所有计数收集到一个数组中,然后在最后总结它(allResults.reduce(0, +)),这有点浪费,但也不是世界末日.我是这样离开的,因为accumulateResults在你希望在数组中积累部分结果的其他情况下可以使用它.

现在最后一件事,一个真正的accumulateResults函数可能是元素类型的通用函数,我们也可以消除partialResultsSoFar外部函数的参数.那这个呢?

func accumulateResults<T>(eventLoop: EventLoop,
                          getPartial: @escaping () -> EventLoopFuture<T?>) -> EventLoopFuture<[T]> {
    // this is an inner function just to hide it from the outside which carries the accumulator
    func accumulateResults<T>(eventLoop: EventLoop,
                              partialResultsSoFar: [T] /* our accumulator */,
                              getPartial: @escaping () -> EventLoopFuture<T?>) -> EventLoopFuture<[T]> {
        // let's run getPartial once
        return getPartial().then { partialResult in
            // we got a partial result, let's check what it is
            if let partialResult = partialResult {
                // another intermediate results, let's accumulate and call getPartial again
                return accumulateResults(eventLoop: eventLoop,
                                         partialResultsSoFar: partialResultsSoFar + [partialResult],
                                         getPartial: getPartial)
            } else {
                // we've got all the partial results, yay, let's fulfill the overall future
                return eventLoop.newSucceededFuture(result: partialResultsSoFar)
            }
        }
    }
    return accumulateResults(eventLoop: eventLoop, partialResultsSoFar: [], getPartial: getPartial)
}
Run Code Online (Sandbox Code Playgroud)

编辑:编辑后,您的问题表明您实际上并不想积累中间结果.所以我的猜测是,您希望在收到每个中间结果后进行一些处理.如果这是你想要做的,也许试试这个:

func processPartialResults<T, V>(eventLoop: EventLoop,
                                 process: @escaping (T) -> EventLoopFuture<V>,
                                 getPartial: @escaping () -> EventLoopFuture<T?>) -> EventLoopFuture<V?> {
    func processPartialResults<T, V>(eventLoop: EventLoop,
                                     soFar: V?,
                                     process: @escaping (T) -> EventLoopFuture<V>,
                                     getPartial: @escaping () -> EventLoopFuture<T?>) -> EventLoopFuture<V?> {
        // let's run getPartial once
        return getPartial().then { partialResult in
            // we got a partial result, let's check what it is
            if let partialResult = partialResult {
                // another intermediate results, let's call the process function and move on
                return process(partialResult).then { v in
                    return processPartialResults(eventLoop: eventLoop, soFar: v, process: process, getPartial: getPartial)
                }
            } else {
                // we've got all the partial results, yay, let's fulfill the overall future
                return eventLoop.newSucceededFuture(result: soFar)
            }
        }
    }
    return processPartialResults(eventLoop: eventLoop, soFar: nil, process: process, getPartial: getPartial)
}
Run Code Online (Sandbox Code Playgroud)

这将(如前所述)运行getPartial直到它返回nil但不是累积所有getPartial结果,而是调用process哪个获得部分结果并且可以进行进一步处理.getPartialEventLoopFuture process满足回报时,将发生下一个调用.

那更接近你想要的吗?

注意:我EventLoopFuture在这里使用了SwiftNIO的类型,在Vapor中你只需要使用它,Future但代码的其余部分应该是相同的.