1

I have a cloud function calling another cloud function in python. My issue is that when I call the next function, the first one waits for its execution or times out.

The key is that this is about Google Cloud Functions. Particularly as mismatch between function timeout and maximum API call rate. My issue is that the function's maximum timeout (540 seconds) is shorter than the time I need to make the required API calls and that I don't want to create more triggers.

How can I make the first (the "caller") finish, after calling the second function, that does its work? Some sample code:

# main.py
# url: this-particular-cloud-function

# function initiated with a post request containing {"previous_tin_index": 0}
import requests
import time
import logging

final_tin_index = 100

def eat_spam(request):
  started_eating_spam = time.time()

  spam_json = request.get_json()
  spam_to_eat = spam_json["previous_tin_index"]

  for spam in range(spam_to_eat):
    time.sleep(5)
    previous_tin_index += 1
    logging.info("I hate spam....")
    finished_previous_spam_time = time.time() - started_eating_spam

  if finished_previous_spam_time >= 10:
    logging.info("Make it stop!")
    requests.post("this-particular-cloud-function", json={"previous_tin_index": previous_tin_index})

  return "200"

EDIT: I know that the inherent problem is that the function never reaches the return value. I am wondering if this can be fixed, other than, for example, rewriting the code into a Javascript promise.

P.S. I looked at the Cloud Documentation, but python seems to be lacking in the particular example.

GregK
  • 571
  • 6
  • 15

1 Answers1

0

This may solve your issue.

    def f1(x):
            print('f1', x)
            return f2, (x+1,)
    def f2(x):
            print('f2', x)
            return f1, (x+1,)

    f, args = f1, (0,)
    while True:
            f, args = f(*args)

Credits to this post.

Although I believe that the issue in your case is the work flow. You are returning a value but the problem is that you never reach that point in your code. Let's assume that you have foo1() and inside foo1() you call foo2(). Then foo()2 is starting to be executed but before you return to foo1() and continue until you reach the return command, foo1() is timed out.

In case your issue isn’t solved then the problem may be at the second function, so it will may be needed to review this function in order to resolve your problem.

Please let me know if this was helpful.

tzovourn
  • 1,293
  • 8
  • 18
  • Sorry for the late reply and thank you George! The issue is clear, my use case requires multiple function executions, however. This is because I am calling an API with limited quota that would exceed my function's timeout. Also, I do not want to make multiple triggers. I was just wondering if that was easily accomplishable in Python. Interesting idea, returning a function, though! Thank you for that George – GregK Sep 21 '19 at 02:31