8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Tips: RubyでCloud Functionsを書くときに、レスポンスだけ先に返して処理を続ける方法

Last updated at Posted at 2023-04-18

この記事は何

最近RubyでCloud Functionsを書くときに、レスポンスだけ先に返して処理を続ける必要があったので、その方法を紹介する記事です。

Cloud Functionsで開発していた時の課題

Cloud Functionsを使ってSlackでスラッシュコマンドを用いたボットの開発を行っていたのですが、開発するにあたり、以下のような問題が発生していました。

これらの問題を解決する方法としては https://qiita.com/saken649/items/b70e462ae41614b72f77
のように

  1. レスポンスを先に返す
    • 「Running...」のようなレスポンスだけ先に返す
  2. 自在の処理はレスポンスを返した後に続ける
  3. 処理が終わったタイミングで、SlackのAPIを用いて結果をポストする

というような処理を行う方法が一番シンプルです。

Rubyでの実現方法

https://qiita.com/saken649/items/b70e462ae41614b72f77 はNode.jsで実装されていますが、
Rubyでも同じようなことができないか調べてみました。
結論から言うと、Threadを用いることで実現ができます。
以下のようなコードを書くことで、先にレスポンスを返し、処理を続けることができました。

require 'functions_framework'

FunctionsFramework.http 'function' do |request|
  Thread.new do
    very_long_transaction
    'OK'
  end
  
  'Running...'
end
8
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?