router.route(“ / api / *”)。handler内でコルーチンを使用する方法は?

Nov 22 2020

次のように、ルートハンドララムダ内でコルーチンを使用しようとしています。

  private suspend fun createRoutes(router: Router, auth: OAuth2Auth): Unit {


    val oauth2 = OAuth2AuthHandler.create(vertx, auth)
    val authz = KeycloakAuthorization.create()


    router.route().handler(LoggerHandler.create())

    router.route("/api/*").handler(oauth2)

     router.route("/api/greet").handler {

      println(RoleBasedAuthorization.create("ad-admins").match(it.user()))

      authz.getAuthorizations(it.user()).await()
    }

  }

コンパイラはauthz.getAuthorizations(it.user()).await()について文句を言いSuspension functions can be called only within coroutine bodyます。私は何が間違っているのですか?

コード全体:

class MainVerticle : CoroutineVerticle() {

  private suspend fun initConfig(): JsonObject {
    val yamlConfigOpts = ConfigStoreOptions()
      .setFormat("yaml")
      .setType("file")
      .setConfig(JsonObject().put("path", "config.yaml"))

    val configRetrieverOpts = ConfigRetrieverOptions()
      .addStore(yamlConfigOpts)

    val configRetriever = ConfigRetriever.create(vertx, configRetrieverOpts)

    return configRetriever.config.await()
  }


  private suspend fun createJwtAuth(): OAuth2Auth =

    KeycloakAuth.discover(
      vertx,
      OAuth2Options()
        .setFlow(OAuth2FlowType.AUTH_CODE)
        .setClientID("svc")
        .setClientSecret("9d782e45-67e7-44b1-9b74-864f45f9a18f")
        .setSite("https://oic.dev.databaker.io/auth/realms/databaker")
    ).await()


  private suspend fun createRoutes(router: Router, auth: OAuth2Auth): Unit {


    val oauth2 = OAuth2AuthHandler.create(vertx, auth)
    val authz = KeycloakAuthorization.create()


    router.route().handler(LoggerHandler.create())

    router.route("/api/*").handler(oauth2)

    router.route("/api/greet").handler {

      println(RoleBasedAuthorization.create("ad-admins").match(it.user()))

      authz.getAuthorizations(it.user()).await()
    }

  }


  private suspend fun server(router: Router): HttpServer {
    val server = vertx.createHttpServer()

    return server.requestHandler(router)
      .listen(8080)
      .onSuccess {
        println("HTTP server started on port ${it.actualPort()}") } .onFailure { println("Failed to start the server. Reason ${it.message}")
      }
      .await()
  }


  override suspend fun start() {

    val router = Router.router(vertx)


    createRoutes(router, createJwtAuth())
    server(router)

  }

}

ヒント:Vertx 4.0.0RC1を使用しています

回答

1 tsegismont Nov 23 2020 at 09:36

コンパイラauthz.getAuthorizations(it.user()).await()は、中断された関数で呼び出されないため、Vert.xWebルートハンドラから呼び出されます。

呼び出しをlaunch:でラップする必要があります。

router.route("/api/greet").handler {
  println(RoleBasedAuthorization.create("ad-admins").match(it.user()))
  launch {
    authz.getAuthorizations(it.user()).await()
  }
}

このコードがで定義されているCoroutineVerticle場合、コルーチンはバーティクルコンテキスト(およびバーティクルのイベントループで呼び出されるコード)にバインドされます。