ktorio / ktor

Framework for quickly creating connected applications in Kotlin with minimal effort
https://ktor.io
Apache License 2.0
13.03k stars 1.07k forks source link

Can't call App Engine APIs on Google App Engine standard environment #1486

Open emathis11 opened 4 years ago

emathis11 commented 4 years ago

I have followed the instructions to run a Ktor server on App Engine standard environment but unfortunately, this only works as long as you're not calling any App Engine APIs. When you call any of them, it fails with the following error:

Can't make API call memcache.Set in a thread that is neither the original request thread nor a thread created by ThreadManager

The Google Cloud java library APIs don't have this threading limitation, but unfortunately I can't use them as I need to access the App Engine Memcache service, which is only available through the App Engine APIs.

Is there any way around it?

cy6erGn0m commented 4 years ago

You need to run your API calls in withContext(dispatcher) { } block, where dispatcher is a dispatcher scheduling via ThreadManager.

mos8502 commented 4 years ago

You need to run your API calls in withContext(dispatcher) { } block, where dispatcher is a dispatcher scheduling via ThreadManager.

The problem is that it seems like that the thread needs to be created on the thread of the request. So far I have only managed to achieve this by subclassing ServletApplicationEngine and in serve initialise a CoroutineDispatcher from a ThreadPoolService with one core thread using ThreadManager.currentRequestThreadFactory().

Then making sure that the thread is created before super.serve is called by invoking prestartAllCoreThreads on the executor.

This is extremely hacky and will definitely cause issues if the same servlet instance is used to serve multiple requests

cy6erGn0m commented 4 years ago

Thanks for the hint. I'll think how to integrate it properly.

oleg-larshin commented 4 years ago

Please check the following ticket on YouTrack for follow-ups to this issue. GitHub issues will be closed in the coming weeks.

lmiskovic commented 1 year ago

Hey, I've posted a question on youtrack and also quoting it here as I'm not sure what is currently being used to track issues

Hey, is there any news related to this issue? I'm currently trying to call App engine APIs and still receiving this error

java.lang.NullPointerException: Current thread is not associated with any request and is not a background thread

I'm using latest Ktor version, 2.3.2 and it is kinda strange that this was not addressed yet, am I missing something, using it wrongly maybe?

This is the sdk I'm using: implementation("com.google.appengine:appengine-java-sdk:2.0.16") and I'm trying to send an email from Ktor using app engine's Java.mail implementation.

https://youtrack.jetbrains.com/issue/KTOR-513