草庐IT

swift - 使用Vapor 3创建和使用游标

coder 2023-09-06 原文

这可能是一 jar 蠕虫,我会尽力描述这个问题。我们有一个长期运行的数据处理工作。我们的行动数据库会每晚添加一次,并且会处理未完成的行动。处理每晚的操作大约需要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: ())
}

现在这不起作用,因为我正在调用 wait(),并且收到错误“前提条件失败:在EventLoop上不得调用wait()” ,这很公平。我面临的问题之一是,我不知道您如何离开主事件循环,以在后台线程上运行类似的事情。我知道BlockingIOThreadPool,但这似乎仍然可以在同一EventLoop上运行,并且仍然会导致错误。虽然我可以从理论上提出越来越多的复杂方法来实现这一目标,但我希望我缺少一个优雅的解决方案,也许对SwiftNIO和Fluent有更深入了解的人可以提供帮助。

编辑:明确地说,这样做的目的显然是不总计数据库中的操作数。目标是使用游标同步处理每个 Action 。当我读入结果时,我检测到 Action 中的更改,然后将它们的批处理丢给处理线程。当所有线程都忙时,直到它们完成,我才从游标再次开始读取。

这些 Action 很多,单次运行最多4500万次。聚集promise和递归似乎不是一个好主意,当我尝试使用它时,仅出于此目的,服务器挂起了。

这是一项处理密集型任务,可以在单个线程上运行几天,因此我不必担心创建新线程。问题是我无法弄清楚如何在命令中使用wait()函数,因为我需要一个容器来创建数据库连接,而我只能访问的一个容器就是 context.container 调用wait()这样会导致上述错误。

TIA

最佳答案

好的,正如您所知道的,问题出在以下几行:

while ... {
    ...
    try connection.raw("...").all(decoding: RecRegAction.self).wait()
    ...
}

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

让我们看看我们必须解决什么问题:

就像您说的
  • 一样,我们可以仅将这个.wait()放在不是事件循环线程之一的另一个线程上。为此,任何非EventLoop线程都可以:DispatchQueue或您可以使用BlockingIOThreadPool(不在EventLoop上运行)
  • 我们可以将您的代码重写为异步

  • 两种解决方案都可以使用,但是(1)确实不建议使用,因为您将刻录整个(内核)线程只是为了等待结果。而且DispatchBlockingIOThreadPool都具有它们愿意产生的有限数量的线程,因此,如果您经常执行此操作,则可能会耗尽线程,因此将花费更长的时间。

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

    为了使事情变得简单,让我们看一个与您的功能非常相似的功能。我们假定将提供此功能,就像您的代码中一样
    /// delivers partial results (integers) and `nil` if no further elements are available
    func deliverPartialResult() -> EventLoopFuture<Int?> {
        ...
    }
    

    我们现在想要的是一个新功能
    func deliverFullResult() -> EventLoopFuture<[Int]>
    

    请注意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)
            }
        }
    }
    

    给定accumulateResults,实现deliverFullResult不再太困难了:
    func deliverFullResult() -> EventLoopFuture<[Int]> {
        return accumulateResults(eventLoop: myCurrentEventLoop,
                                 partialResultsSoFar: [],
                                 getPartial: deliverPartialResult)
    }
    

    但是,让我们进一步了解accumulateResults的作用:
  • 它会调用一次getPartial,然后在调用它时
  • 检查我们是否有
  • 是部分结果,在这种情况下,我们将其与其他partialResultsSoFar一起记住,然后返回(1)
  • nil意味着partialResultsSoFar就是我们所能得到的,我们将返回迄今为止已收集的所有内容的新成功的 future

  • 确实是这样。我们在这里所做的是将同步循环变成异步递归。

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

    信不信由你,但这应该可以正常工作(未经测试):
    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, +)
    }
    

    所有这些的结果将是一个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)
    }
    

    编辑:编辑后,您的问题表明您实际上并不希望累积中间结果。所以我的猜测是,您希望在收到每个中间结果之后进行一些处理。如果那是您要执行的操作,请尝试以下操作:
    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)
    }
    

    这将(像以前一样)运行getPartial,直到返回nil为止,但它不会累积所有getPartial的结果,而是调用process,它获得了部分结果并可以做一些进一步的处理。当getPartial EventLoopFuture返回满足时,将发生下一个process调用。

    这更接近您想要的吗?

    注意:我在这里使用了SwiftNIO的EventLoopFuture类型,在Vapor中,您将只使用Future,但是其余代码应该相同。

    关于swift - 使用Vapor 3创建和使用游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51625050/

    有关swift - 使用Vapor 3创建和使用游标的更多相关文章

    1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

      我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

    2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

      我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

    3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

      类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

    4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

      很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

    5. ruby - 在 Ruby 中使用匿名模块 - 2

      假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

    6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

      我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

    7. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

      关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

    8. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

      我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

    9. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

      我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

    10. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

      我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

    随机推荐