From c9193bd9e372aa46f387565036a87fdc9772c905 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 7 Oct 2021 19:27:53 +0000 Subject: [PATCH 1/2] feat: add context manager support in client chore: fix docstring for first attribute of protos committer: @busunkim96 PiperOrigin-RevId: 401271153 Source-Link: https://github.com/googleapis/googleapis/commit/787f8c9a731f44e74a90b9847d48659ca9462d10 Source-Link: https://github.com/googleapis/googleapis-gen/commit/81decffe9fc72396a8153e756d1d67a6eecfd620 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiODFkZWNmZmU5ZmM3MjM5NmE4MTUzZTc1NmQxZDY3YTZlZWNmZDYyMCJ9 --- owl-bot-staging/v3/.coveragerc | 17 + owl-bot-staging/v3/MANIFEST.in | 2 + owl-bot-staging/v3/README.rst | 49 + owl-bot-staging/v3/docs/conf.py | 376 ++ .../v3/docs/dialogflowcx_v3/agents.rst | 10 + .../v3/docs/dialogflowcx_v3/deployments.rst | 10 + .../v3/docs/dialogflowcx_v3/entity_types.rst | 10 + .../v3/docs/dialogflowcx_v3/environments.rst | 10 + .../v3/docs/dialogflowcx_v3/experiments.rst | 10 + .../v3/docs/dialogflowcx_v3/flows.rst | 10 + .../v3/docs/dialogflowcx_v3/intents.rst | 10 + .../v3/docs/dialogflowcx_v3/pages.rst | 10 + .../security_settings_service.rst | 10 + .../v3/docs/dialogflowcx_v3/services.rst | 20 + .../dialogflowcx_v3/session_entity_types.rst | 10 + .../v3/docs/dialogflowcx_v3/sessions.rst | 6 + .../v3/docs/dialogflowcx_v3/test_cases.rst | 10 + .../transition_route_groups.rst | 10 + .../v3/docs/dialogflowcx_v3/types.rst | 7 + .../v3/docs/dialogflowcx_v3/versions.rst | 10 + .../v3/docs/dialogflowcx_v3/webhooks.rst | 10 + owl-bot-staging/v3/docs/index.rst | 7 + .../v3/google/cloud/dialogflowcx/__init__.py | 475 ++ .../v3/google/cloud/dialogflowcx/py.typed | 2 + .../google/cloud/dialogflowcx_v3/__init__.py | 476 ++ .../cloud/dialogflowcx_v3/gapic_metadata.json | 1159 +++++ .../v3/google/cloud/dialogflowcx_v3/py.typed | 2 + .../dialogflowcx_v3/services/__init__.py | 15 + .../services/agents/__init__.py | 22 + .../services/agents/async_client.py | 928 ++++ .../dialogflowcx_v3/services/agents/client.py | 1173 +++++ .../dialogflowcx_v3/services/agents/pagers.py | 140 + .../services/agents/transports/__init__.py | 33 + .../services/agents/transports/base.py | 299 ++ .../services/agents/transports/grpc.py | 524 +++ .../agents/transports/grpc_asyncio.py | 529 +++ .../services/deployments/__init__.py | 22 + .../services/deployments/async_client.py | 347 ++ .../services/deployments/client.py | 571 +++ .../services/deployments/pagers.py | 140 + .../deployments/transports/__init__.py | 33 + .../services/deployments/transports/base.py | 192 + .../services/deployments/transports/grpc.py | 283 ++ .../deployments/transports/grpc_asyncio.py | 288 ++ .../services/entity_types/__init__.py | 22 + .../services/entity_types/async_client.py | 673 +++ .../services/entity_types/client.py | 870 ++++ .../services/entity_types/pagers.py | 140 + .../entity_types/transports/__init__.py | 33 + .../services/entity_types/transports/base.py | 236 + .../services/entity_types/transports/grpc.py | 374 ++ .../entity_types/transports/grpc_asyncio.py | 379 ++ .../services/environments/__init__.py | 22 + .../services/environments/async_client.py | 995 ++++ .../services/environments/client.py | 1230 +++++ .../services/environments/pagers.py | 384 ++ .../environments/transports/__init__.py | 33 + .../services/environments/transports/base.py | 299 ++ .../services/environments/transports/grpc.py | 534 +++ .../environments/transports/grpc_asyncio.py | 539 +++ .../services/experiments/__init__.py | 22 + .../services/experiments/async_client.py | 740 +++ .../services/experiments/client.py | 946 ++++ .../services/experiments/pagers.py | 140 + .../experiments/transports/__init__.py | 33 + .../services/experiments/transports/base.py | 264 ++ .../services/experiments/transports/grpc.py | 424 ++ .../experiments/transports/grpc_asyncio.py | 429 ++ .../services/flows/__init__.py | 22 + .../services/flows/async_client.py | 1057 +++++ .../dialogflowcx_v3/services/flows/client.py | 1302 ++++++ .../dialogflowcx_v3/services/flows/pagers.py | 140 + .../services/flows/transports/__init__.py | 33 + .../services/flows/transports/base.py | 313 ++ .../services/flows/transports/grpc.py | 564 +++ .../services/flows/transports/grpc_asyncio.py | 569 +++ .../services/intents/__init__.py | 22 + .../services/intents/async_client.py | 594 +++ .../services/intents/client.py | 800 ++++ .../services/intents/pagers.py | 140 + .../services/intents/transports/__init__.py | 33 + .../services/intents/transports/base.py | 236 + .../services/intents/transports/grpc.py | 374 ++ .../intents/transports/grpc_asyncio.py | 379 ++ .../services/pages/__init__.py | 22 + .../services/pages/async_client.py | 645 +++ .../dialogflowcx_v3/services/pages/client.py | 887 ++++ .../dialogflowcx_v3/services/pages/pagers.py | 140 + .../services/pages/transports/__init__.py | 33 + .../services/pages/transports/base.py | 236 + .../services/pages/transports/grpc.py | 372 ++ .../services/pages/transports/grpc_asyncio.py | 377 ++ .../security_settings_service/__init__.py | 22 + .../security_settings_service/async_client.py | 592 +++ .../security_settings_service/client.py | 807 ++++ .../security_settings_service/pagers.py | 140 + .../transports/__init__.py | 33 + .../transports/base.py | 236 + .../transports/grpc.py | 365 ++ .../transports/grpc_asyncio.py | 370 ++ .../services/session_entity_types/__init__.py | 22 + .../session_entity_types/async_client.py | 634 +++ .../services/session_entity_types/client.py | 831 ++++ .../services/session_entity_types/pagers.py | 140 + .../transports/__init__.py | 33 + .../session_entity_types/transports/base.py | 236 + .../session_entity_types/transports/grpc.py | 362 ++ .../transports/grpc_asyncio.py | 367 ++ .../services/sessions/__init__.py | 22 + .../services/sessions/async_client.py | 464 ++ .../services/sessions/client.py | 726 +++ .../services/sessions/transports/__init__.py | 33 + .../services/sessions/transports/base.py | 226 + .../services/sessions/transports/grpc.py | 356 ++ .../sessions/transports/grpc_asyncio.py | 361 ++ .../services/test_cases/__init__.py | 22 + .../services/test_cases/async_client.py | 1115 +++++ .../services/test_cases/client.py | 1398 ++++++ .../services/test_cases/pagers.py | 262 ++ .../test_cases/transports/__init__.py | 33 + .../services/test_cases/transports/base.py | 341 ++ .../services/test_cases/transports/grpc.py | 608 +++ .../test_cases/transports/grpc_asyncio.py | 613 +++ .../transition_route_groups/__init__.py | 22 + .../transition_route_groups/async_client.py | 607 +++ .../transition_route_groups/client.py | 840 ++++ .../transition_route_groups/pagers.py | 140 + .../transports/__init__.py | 33 + .../transports/base.py | 236 + .../transports/grpc.py | 379 ++ .../transports/grpc_asyncio.py | 384 ++ .../services/versions/__init__.py | 22 + .../services/versions/async_client.py | 708 +++ .../services/versions/client.py | 905 ++++ .../services/versions/pagers.py | 140 + .../services/versions/transports/__init__.py | 33 + .../services/versions/transports/base.py | 257 ++ .../services/versions/transports/grpc.py | 431 ++ .../versions/transports/grpc_asyncio.py | 436 ++ .../services/webhooks/__init__.py | 22 + .../services/webhooks/async_client.py | 583 +++ .../services/webhooks/client.py | 789 ++++ .../services/webhooks/pagers.py | 140 + .../services/webhooks/transports/__init__.py | 33 + .../services/webhooks/transports/base.py | 236 + .../services/webhooks/transports/grpc.py | 362 ++ .../webhooks/transports/grpc_asyncio.py | 367 ++ .../cloud/dialogflowcx_v3/types/__init__.py | 454 ++ .../types/advanced_settings.py | 71 + .../cloud/dialogflowcx_v3/types/agent.py | 505 ++ .../dialogflowcx_v3/types/audio_config.py | 359 ++ .../cloud/dialogflowcx_v3/types/deployment.py | 202 + .../dialogflowcx_v3/types/entity_type.py | 427 ++ .../dialogflowcx_v3/types/environment.py | 587 +++ .../cloud/dialogflowcx_v3/types/experiment.py | 703 +++ .../cloud/dialogflowcx_v3/types/flow.py | 642 +++ .../dialogflowcx_v3/types/fulfillment.py | 200 + .../cloud/dialogflowcx_v3/types/intent.py | 476 ++ .../cloud/dialogflowcx_v3/types/page.py | 731 +++ .../dialogflowcx_v3/types/response_message.py | 343 ++ .../types/security_settings.py | 327 ++ .../cloud/dialogflowcx_v3/types/session.py | 1237 +++++ .../types/session_entity_type.py | 254 ++ .../cloud/dialogflowcx_v3/types/test_case.py | 1268 ++++++ .../types/transition_route_group.py | 307 ++ .../types/validation_message.py | 115 + .../cloud/dialogflowcx_v3/types/version.py | 293 ++ .../cloud/dialogflowcx_v3/types/webhook.py | 799 ++++ owl-bot-staging/v3/mypy.ini | 3 + owl-bot-staging/v3/noxfile.py | 132 + .../scripts/fixup_dialogflowcx_v3_keywords.py | 269 ++ owl-bot-staging/v3/setup.py | 54 + owl-bot-staging/v3/tests/__init__.py | 16 + owl-bot-staging/v3/tests/unit/__init__.py | 16 + .../v3/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/dialogflowcx_v3/__init__.py | 16 + .../unit/gapic/dialogflowcx_v3/test_agents.py | 3298 ++++++++++++++ .../gapic/dialogflowcx_v3/test_deployments.py | 1725 +++++++ .../dialogflowcx_v3/test_entity_types.py | 2403 ++++++++++ .../dialogflowcx_v3/test_environments.py | 3622 +++++++++++++++ .../gapic/dialogflowcx_v3/test_experiments.py | 2916 ++++++++++++ .../unit/gapic/dialogflowcx_v3/test_flows.py | 3457 ++++++++++++++ .../gapic/dialogflowcx_v3/test_intents.py | 2414 ++++++++++ .../unit/gapic/dialogflowcx_v3/test_pages.py | 2489 ++++++++++ .../test_security_settings_service.py | 2458 ++++++++++ .../test_session_entity_types.py | 2358 ++++++++++ .../gapic/dialogflowcx_v3/test_sessions.py | 1726 +++++++ .../gapic/dialogflowcx_v3/test_test_cases.py | 4046 +++++++++++++++++ .../test_transition_route_groups.py | 2455 ++++++++++ .../gapic/dialogflowcx_v3/test_versions.py | 2643 +++++++++++ .../gapic/dialogflowcx_v3/test_webhooks.py | 2394 ++++++++++ owl-bot-staging/v3beta1/.coveragerc | 17 + owl-bot-staging/v3beta1/MANIFEST.in | 2 + owl-bot-staging/v3beta1/README.rst | 49 + owl-bot-staging/v3beta1/docs/conf.py | 376 ++ .../docs/dialogflowcx_v3beta1/agents.rst | 10 + .../docs/dialogflowcx_v3beta1/deployments.rst | 10 + .../dialogflowcx_v3beta1/entity_types.rst | 10 + .../dialogflowcx_v3beta1/environments.rst | 10 + .../docs/dialogflowcx_v3beta1/experiments.rst | 10 + .../docs/dialogflowcx_v3beta1/flows.rst | 10 + .../docs/dialogflowcx_v3beta1/intents.rst | 10 + .../docs/dialogflowcx_v3beta1/pages.rst | 10 + .../security_settings_service.rst | 10 + .../docs/dialogflowcx_v3beta1/services.rst | 20 + .../session_entity_types.rst | 10 + .../docs/dialogflowcx_v3beta1/sessions.rst | 6 + .../docs/dialogflowcx_v3beta1/test_cases.rst | 10 + .../transition_route_groups.rst | 10 + .../docs/dialogflowcx_v3beta1/types.rst | 7 + .../docs/dialogflowcx_v3beta1/versions.rst | 10 + .../docs/dialogflowcx_v3beta1/webhooks.rst | 10 + owl-bot-staging/v3beta1/docs/index.rst | 7 + .../google/cloud/dialogflowcx/__init__.py | 475 ++ .../google/cloud/dialogflowcx/py.typed | 2 + .../cloud/dialogflowcx_v3beta1/__init__.py | 476 ++ .../dialogflowcx_v3beta1/gapic_metadata.json | 1159 +++++ .../cloud/dialogflowcx_v3beta1/py.typed | 2 + .../dialogflowcx_v3beta1/services/__init__.py | 15 + .../services/agents/__init__.py | 22 + .../services/agents/async_client.py | 930 ++++ .../services/agents/client.py | 1175 +++++ .../services/agents/pagers.py | 140 + .../services/agents/transports/__init__.py | 33 + .../services/agents/transports/base.py | 299 ++ .../services/agents/transports/grpc.py | 525 +++ .../agents/transports/grpc_asyncio.py | 530 +++ .../services/deployments/__init__.py | 22 + .../services/deployments/async_client.py | 347 ++ .../services/deployments/client.py | 571 +++ .../services/deployments/pagers.py | 140 + .../deployments/transports/__init__.py | 33 + .../services/deployments/transports/base.py | 192 + .../services/deployments/transports/grpc.py | 283 ++ .../deployments/transports/grpc_asyncio.py | 288 ++ .../services/entity_types/__init__.py | 22 + .../services/entity_types/async_client.py | 669 +++ .../services/entity_types/client.py | 866 ++++ .../services/entity_types/pagers.py | 140 + .../entity_types/transports/__init__.py | 33 + .../services/entity_types/transports/base.py | 236 + .../services/entity_types/transports/grpc.py | 370 ++ .../entity_types/transports/grpc_asyncio.py | 375 ++ .../services/environments/__init__.py | 22 + .../services/environments/async_client.py | 995 ++++ .../services/environments/client.py | 1230 +++++ .../services/environments/pagers.py | 384 ++ .../environments/transports/__init__.py | 33 + .../services/environments/transports/base.py | 299 ++ .../services/environments/transports/grpc.py | 534 +++ .../environments/transports/grpc_asyncio.py | 539 +++ .../services/experiments/__init__.py | 22 + .../services/experiments/async_client.py | 742 +++ .../services/experiments/client.py | 948 ++++ .../services/experiments/pagers.py | 140 + .../experiments/transports/__init__.py | 33 + .../services/experiments/transports/base.py | 264 ++ .../services/experiments/transports/grpc.py | 426 ++ .../experiments/transports/grpc_asyncio.py | 431 ++ .../services/flows/__init__.py | 22 + .../services/flows/async_client.py | 1059 +++++ .../services/flows/client.py | 1304 ++++++ .../services/flows/pagers.py | 140 + .../services/flows/transports/__init__.py | 33 + .../services/flows/transports/base.py | 313 ++ .../services/flows/transports/grpc.py | 565 +++ .../services/flows/transports/grpc_asyncio.py | 570 +++ .../services/intents/__init__.py | 22 + .../services/intents/async_client.py | 594 +++ .../services/intents/client.py | 800 ++++ .../services/intents/pagers.py | 140 + .../services/intents/transports/__init__.py | 33 + .../services/intents/transports/base.py | 236 + .../services/intents/transports/grpc.py | 374 ++ .../intents/transports/grpc_asyncio.py | 379 ++ .../services/pages/__init__.py | 22 + .../services/pages/async_client.py | 635 +++ .../services/pages/client.py | 877 ++++ .../services/pages/pagers.py | 140 + .../services/pages/transports/__init__.py | 33 + .../services/pages/transports/base.py | 236 + .../services/pages/transports/grpc.py | 361 ++ .../services/pages/transports/grpc_asyncio.py | 366 ++ .../security_settings_service/__init__.py | 22 + .../security_settings_service/async_client.py | 592 +++ .../security_settings_service/client.py | 807 ++++ .../security_settings_service/pagers.py | 140 + .../transports/__init__.py | 33 + .../transports/base.py | 236 + .../transports/grpc.py | 365 ++ .../transports/grpc_asyncio.py | 370 ++ .../services/session_entity_types/__init__.py | 22 + .../session_entity_types/async_client.py | 637 +++ .../services/session_entity_types/client.py | 834 ++++ .../services/session_entity_types/pagers.py | 140 + .../transports/__init__.py | 33 + .../session_entity_types/transports/base.py | 236 + .../session_entity_types/transports/grpc.py | 362 ++ .../transports/grpc_asyncio.py | 367 ++ .../services/sessions/__init__.py | 22 + .../services/sessions/async_client.py | 464 ++ .../services/sessions/client.py | 726 +++ .../services/sessions/transports/__init__.py | 33 + .../services/sessions/transports/base.py | 226 + .../services/sessions/transports/grpc.py | 356 ++ .../sessions/transports/grpc_asyncio.py | 361 ++ .../services/test_cases/__init__.py | 22 + .../services/test_cases/async_client.py | 1115 +++++ .../services/test_cases/client.py | 1398 ++++++ .../services/test_cases/pagers.py | 262 ++ .../test_cases/transports/__init__.py | 33 + .../services/test_cases/transports/base.py | 341 ++ .../services/test_cases/transports/grpc.py | 608 +++ .../test_cases/transports/grpc_asyncio.py | 613 +++ .../transition_route_groups/__init__.py | 22 + .../transition_route_groups/async_client.py | 607 +++ .../transition_route_groups/client.py | 840 ++++ .../transition_route_groups/pagers.py | 140 + .../transports/__init__.py | 33 + .../transports/base.py | 236 + .../transports/grpc.py | 379 ++ .../transports/grpc_asyncio.py | 384 ++ .../services/versions/__init__.py | 22 + .../services/versions/async_client.py | 711 +++ .../services/versions/client.py | 908 ++++ .../services/versions/pagers.py | 140 + .../services/versions/transports/__init__.py | 33 + .../services/versions/transports/base.py | 257 ++ .../services/versions/transports/grpc.py | 432 ++ .../versions/transports/grpc_asyncio.py | 437 ++ .../services/webhooks/__init__.py | 22 + .../services/webhooks/async_client.py | 583 +++ .../services/webhooks/client.py | 789 ++++ .../services/webhooks/pagers.py | 140 + .../services/webhooks/transports/__init__.py | 33 + .../services/webhooks/transports/base.py | 236 + .../services/webhooks/transports/grpc.py | 362 ++ .../webhooks/transports/grpc_asyncio.py | 367 ++ .../dialogflowcx_v3beta1/types/__init__.py | 454 ++ .../types/advanced_settings.py | 71 + .../cloud/dialogflowcx_v3beta1/types/agent.py | 505 ++ .../types/audio_config.py | 360 ++ .../dialogflowcx_v3beta1/types/deployment.py | 202 + .../dialogflowcx_v3beta1/types/entity_type.py | 427 ++ .../dialogflowcx_v3beta1/types/environment.py | 587 +++ .../dialogflowcx_v3beta1/types/experiment.py | 705 +++ .../cloud/dialogflowcx_v3beta1/types/flow.py | 642 +++ .../dialogflowcx_v3beta1/types/fulfillment.py | 200 + .../dialogflowcx_v3beta1/types/intent.py | 476 ++ .../cloud/dialogflowcx_v3beta1/types/page.py | 731 +++ .../types/response_message.py | 343 ++ .../types/security_settings.py | 327 ++ .../dialogflowcx_v3beta1/types/session.py | 1242 +++++ .../types/session_entity_type.py | 254 ++ .../dialogflowcx_v3beta1/types/test_case.py | 1270 ++++++ .../types/transition_route_group.py | 307 ++ .../types/validation_message.py | 115 + .../dialogflowcx_v3beta1/types/version.py | 296 ++ .../dialogflowcx_v3beta1/types/webhook.py | 801 ++++ owl-bot-staging/v3beta1/mypy.ini | 3 + owl-bot-staging/v3beta1/noxfile.py | 132 + .../fixup_dialogflowcx_v3beta1_keywords.py | 269 ++ owl-bot-staging/v3beta1/setup.py | 54 + owl-bot-staging/v3beta1/tests/__init__.py | 16 + .../v3beta1/tests/unit/__init__.py | 16 + .../v3beta1/tests/unit/gapic/__init__.py | 16 + .../gapic/dialogflowcx_v3beta1/__init__.py | 16 + .../gapic/dialogflowcx_v3beta1/test_agents.py | 3298 ++++++++++++++ .../dialogflowcx_v3beta1/test_deployments.py | 1725 +++++++ .../dialogflowcx_v3beta1/test_entity_types.py | 2403 ++++++++++ .../dialogflowcx_v3beta1/test_environments.py | 3622 +++++++++++++++ .../dialogflowcx_v3beta1/test_experiments.py | 2916 ++++++++++++ .../gapic/dialogflowcx_v3beta1/test_flows.py | 3457 ++++++++++++++ .../dialogflowcx_v3beta1/test_intents.py | 2414 ++++++++++ .../gapic/dialogflowcx_v3beta1/test_pages.py | 2489 ++++++++++ .../test_security_settings_service.py | 2458 ++++++++++ .../test_session_entity_types.py | 2358 ++++++++++ .../dialogflowcx_v3beta1/test_sessions.py | 1726 +++++++ .../dialogflowcx_v3beta1/test_test_cases.py | 4046 +++++++++++++++++ .../test_transition_route_groups.py | 2455 ++++++++++ .../dialogflowcx_v3beta1/test_versions.py | 2643 +++++++++++ .../dialogflowcx_v3beta1/test_webhooks.py | 2394 ++++++++++ 382 files changed, 196849 insertions(+) create mode 100644 owl-bot-staging/v3/.coveragerc create mode 100644 owl-bot-staging/v3/MANIFEST.in create mode 100644 owl-bot-staging/v3/README.rst create mode 100644 owl-bot-staging/v3/docs/conf.py create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/agents.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/deployments.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/entity_types.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/environments.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/experiments.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/flows.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/intents.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/pages.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/security_settings_service.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/services.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/session_entity_types.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/sessions.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/test_cases.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/transition_route_groups.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/types.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/versions.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/webhooks.rst create mode 100644 owl-bot-staging/v3/docs/index.rst create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx/py.typed create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/gapic_metadata.json create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/py.typed create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/advanced_settings.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/agent.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/audio_config.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/deployment.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/entity_type.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/environment.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/experiment.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/flow.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/fulfillment.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/intent.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/page.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/response_message.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/security_settings.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session_entity_type.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/test_case.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/transition_route_group.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/validation_message.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/version.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/webhook.py create mode 100644 owl-bot-staging/v3/mypy.ini create mode 100644 owl-bot-staging/v3/noxfile.py create mode 100644 owl-bot-staging/v3/scripts/fixup_dialogflowcx_v3_keywords.py create mode 100644 owl-bot-staging/v3/setup.py create mode 100644 owl-bot-staging/v3/tests/__init__.py create mode 100644 owl-bot-staging/v3/tests/unit/__init__.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/__init__.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_agents.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_deployments.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_environments.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_experiments.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_flows.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_intents.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_pages.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_sessions.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_versions.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py create mode 100644 owl-bot-staging/v3beta1/.coveragerc create mode 100644 owl-bot-staging/v3beta1/MANIFEST.in create mode 100644 owl-bot-staging/v3beta1/README.rst create mode 100644 owl-bot-staging/v3beta1/docs/conf.py create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/agents.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/deployments.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/entity_types.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/environments.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/experiments.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/flows.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/intents.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/pages.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/security_settings_service.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/services.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/session_entity_types.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/sessions.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/test_cases.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/transition_route_groups.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/types.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/versions.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/webhooks.rst create mode 100644 owl-bot-staging/v3beta1/docs/index.rst create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx/py.typed create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/py.typed create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/deployments/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/deployments/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/deployments/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/deployments/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/deployments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/advanced_settings.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/agent.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/audio_config.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/deployment.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/entity_type.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/environment.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/experiment.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/flow.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/intent.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/page.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/response_message.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/security_settings.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/test_case.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/validation_message.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/version.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/webhook.py create mode 100644 owl-bot-staging/v3beta1/mypy.ini create mode 100644 owl-bot-staging/v3beta1/noxfile.py create mode 100644 owl-bot-staging/v3beta1/scripts/fixup_dialogflowcx_v3beta1_keywords.py create mode 100644 owl-bot-staging/v3beta1/setup.py create mode 100644 owl-bot-staging/v3beta1/tests/__init__.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/__init__.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_deployments.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py diff --git a/owl-bot-staging/v3/.coveragerc b/owl-bot-staging/v3/.coveragerc new file mode 100644 index 00000000..0b2dc233 --- /dev/null +++ b/owl-bot-staging/v3/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/dialogflowcx/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v3/MANIFEST.in b/owl-bot-staging/v3/MANIFEST.in new file mode 100644 index 00000000..83900298 --- /dev/null +++ b/owl-bot-staging/v3/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/dialogflowcx *.py +recursive-include google/cloud/dialogflowcx_v3 *.py diff --git a/owl-bot-staging/v3/README.rst b/owl-bot-staging/v3/README.rst new file mode 100644 index 00000000..bfe57a44 --- /dev/null +++ b/owl-bot-staging/v3/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Dialogflowcx API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Dialogflowcx API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v3/docs/conf.py b/owl-bot-staging/v3/docs/conf.py new file mode 100644 index 00000000..814121cd --- /dev/null +++ b/owl-bot-staging/v3/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-dialogflowcx documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-dialogflowcx" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-dialogflowcx-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-dialogflowcx.tex", + u"google-cloud-dialogflowcx Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-dialogflowcx", + u"Google Cloud Dialogflowcx Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-dialogflowcx", + u"google-cloud-dialogflowcx Documentation", + author, + "google-cloud-dialogflowcx", + "GAPIC library for Google Cloud Dialogflowcx API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/agents.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/agents.rst new file mode 100644 index 00000000..4deb1730 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/agents.rst @@ -0,0 +1,10 @@ +Agents +------------------------ + +.. automodule:: google.cloud.dialogflowcx_v3.services.agents + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.agents.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/deployments.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/deployments.rst new file mode 100644 index 00000000..1f065b30 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/deployments.rst @@ -0,0 +1,10 @@ +Deployments +----------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.deployments + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.deployments.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/entity_types.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/entity_types.rst new file mode 100644 index 00000000..08e4b6e8 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/entity_types.rst @@ -0,0 +1,10 @@ +EntityTypes +----------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.entity_types + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.entity_types.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/environments.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/environments.rst new file mode 100644 index 00000000..246ee15a --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/environments.rst @@ -0,0 +1,10 @@ +Environments +------------------------------ + +.. automodule:: google.cloud.dialogflowcx_v3.services.environments + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.environments.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/experiments.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/experiments.rst new file mode 100644 index 00000000..5cba0e2a --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/experiments.rst @@ -0,0 +1,10 @@ +Experiments +----------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.experiments + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.experiments.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/flows.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/flows.rst new file mode 100644 index 00000000..77f6398e --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/flows.rst @@ -0,0 +1,10 @@ +Flows +----------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.flows + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.flows.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/intents.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/intents.rst new file mode 100644 index 00000000..8b9e6dda --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/intents.rst @@ -0,0 +1,10 @@ +Intents +------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.intents + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.intents.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/pages.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/pages.rst new file mode 100644 index 00000000..0bbfbced --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/pages.rst @@ -0,0 +1,10 @@ +Pages +----------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.pages + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.pages.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/security_settings_service.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/security_settings_service.rst new file mode 100644 index 00000000..4b4fa007 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/security_settings_service.rst @@ -0,0 +1,10 @@ +SecuritySettingsService +----------------------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.security_settings_service + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.security_settings_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/services.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/services.rst new file mode 100644 index 00000000..0868cc62 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/services.rst @@ -0,0 +1,20 @@ +Services for Google Cloud Dialogflowcx v3 API +============================================= +.. toctree:: + :maxdepth: 2 + + agents + deployments + entity_types + environments + experiments + flows + intents + pages + security_settings_service + session_entity_types + sessions + test_cases + transition_route_groups + versions + webhooks diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/session_entity_types.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/session_entity_types.rst new file mode 100644 index 00000000..46ff0f6e --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/session_entity_types.rst @@ -0,0 +1,10 @@ +SessionEntityTypes +------------------------------------ + +.. automodule:: google.cloud.dialogflowcx_v3.services.session_entity_types + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.session_entity_types.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/sessions.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/sessions.rst new file mode 100644 index 00000000..494bceb1 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/sessions.rst @@ -0,0 +1,6 @@ +Sessions +-------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.sessions + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/test_cases.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/test_cases.rst new file mode 100644 index 00000000..3cad4dd4 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/test_cases.rst @@ -0,0 +1,10 @@ +TestCases +--------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.test_cases + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.test_cases.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/transition_route_groups.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/transition_route_groups.rst new file mode 100644 index 00000000..d5549da9 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/transition_route_groups.rst @@ -0,0 +1,10 @@ +TransitionRouteGroups +--------------------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.transition_route_groups + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.transition_route_groups.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/types.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/types.rst new file mode 100644 index 00000000..7e2b1c53 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Dialogflowcx v3 API +========================================== + +.. automodule:: google.cloud.dialogflowcx_v3.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/versions.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/versions.rst new file mode 100644 index 00000000..2d72f02d --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/versions.rst @@ -0,0 +1,10 @@ +Versions +-------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.versions + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.versions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/webhooks.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/webhooks.rst new file mode 100644 index 00000000..2e2f9b8c --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/webhooks.rst @@ -0,0 +1,10 @@ +Webhooks +-------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.webhooks + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.webhooks.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/index.rst b/owl-bot-staging/v3/docs/index.rst new file mode 100644 index 00000000..eaab73b8 --- /dev/null +++ b/owl-bot-staging/v3/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + dialogflowcx_v3/services + dialogflowcx_v3/types diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx/__init__.py new file mode 100644 index 00000000..27c83c1e --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx/__init__.py @@ -0,0 +1,475 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.dialogflowcx_v3.services.agents.client import AgentsClient +from google.cloud.dialogflowcx_v3.services.agents.async_client import AgentsAsyncClient +from google.cloud.dialogflowcx_v3.services.deployments.client import DeploymentsClient +from google.cloud.dialogflowcx_v3.services.deployments.async_client import DeploymentsAsyncClient +from google.cloud.dialogflowcx_v3.services.entity_types.client import EntityTypesClient +from google.cloud.dialogflowcx_v3.services.entity_types.async_client import EntityTypesAsyncClient +from google.cloud.dialogflowcx_v3.services.environments.client import EnvironmentsClient +from google.cloud.dialogflowcx_v3.services.environments.async_client import EnvironmentsAsyncClient +from google.cloud.dialogflowcx_v3.services.experiments.client import ExperimentsClient +from google.cloud.dialogflowcx_v3.services.experiments.async_client import ExperimentsAsyncClient +from google.cloud.dialogflowcx_v3.services.flows.client import FlowsClient +from google.cloud.dialogflowcx_v3.services.flows.async_client import FlowsAsyncClient +from google.cloud.dialogflowcx_v3.services.intents.client import IntentsClient +from google.cloud.dialogflowcx_v3.services.intents.async_client import IntentsAsyncClient +from google.cloud.dialogflowcx_v3.services.pages.client import PagesClient +from google.cloud.dialogflowcx_v3.services.pages.async_client import PagesAsyncClient +from google.cloud.dialogflowcx_v3.services.security_settings_service.client import SecuritySettingsServiceClient +from google.cloud.dialogflowcx_v3.services.security_settings_service.async_client import SecuritySettingsServiceAsyncClient +from google.cloud.dialogflowcx_v3.services.session_entity_types.client import SessionEntityTypesClient +from google.cloud.dialogflowcx_v3.services.session_entity_types.async_client import SessionEntityTypesAsyncClient +from google.cloud.dialogflowcx_v3.services.sessions.client import SessionsClient +from google.cloud.dialogflowcx_v3.services.sessions.async_client import SessionsAsyncClient +from google.cloud.dialogflowcx_v3.services.test_cases.client import TestCasesClient +from google.cloud.dialogflowcx_v3.services.test_cases.async_client import TestCasesAsyncClient +from google.cloud.dialogflowcx_v3.services.transition_route_groups.client import TransitionRouteGroupsClient +from google.cloud.dialogflowcx_v3.services.transition_route_groups.async_client import TransitionRouteGroupsAsyncClient +from google.cloud.dialogflowcx_v3.services.versions.client import VersionsClient +from google.cloud.dialogflowcx_v3.services.versions.async_client import VersionsAsyncClient +from google.cloud.dialogflowcx_v3.services.webhooks.client import WebhooksClient +from google.cloud.dialogflowcx_v3.services.webhooks.async_client import WebhooksAsyncClient + +from google.cloud.dialogflowcx_v3.types.advanced_settings import AdvancedSettings +from google.cloud.dialogflowcx_v3.types.agent import Agent +from google.cloud.dialogflowcx_v3.types.agent import AgentValidationResult +from google.cloud.dialogflowcx_v3.types.agent import CreateAgentRequest +from google.cloud.dialogflowcx_v3.types.agent import DeleteAgentRequest +from google.cloud.dialogflowcx_v3.types.agent import ExportAgentRequest +from google.cloud.dialogflowcx_v3.types.agent import ExportAgentResponse +from google.cloud.dialogflowcx_v3.types.agent import GetAgentRequest +from google.cloud.dialogflowcx_v3.types.agent import GetAgentValidationResultRequest +from google.cloud.dialogflowcx_v3.types.agent import ListAgentsRequest +from google.cloud.dialogflowcx_v3.types.agent import ListAgentsResponse +from google.cloud.dialogflowcx_v3.types.agent import RestoreAgentRequest +from google.cloud.dialogflowcx_v3.types.agent import SpeechToTextSettings +from google.cloud.dialogflowcx_v3.types.agent import UpdateAgentRequest +from google.cloud.dialogflowcx_v3.types.agent import ValidateAgentRequest +from google.cloud.dialogflowcx_v3.types.audio_config import InputAudioConfig +from google.cloud.dialogflowcx_v3.types.audio_config import OutputAudioConfig +from google.cloud.dialogflowcx_v3.types.audio_config import SpeechWordInfo +from google.cloud.dialogflowcx_v3.types.audio_config import SynthesizeSpeechConfig +from google.cloud.dialogflowcx_v3.types.audio_config import VoiceSelectionParams +from google.cloud.dialogflowcx_v3.types.audio_config import AudioEncoding +from google.cloud.dialogflowcx_v3.types.audio_config import OutputAudioEncoding +from google.cloud.dialogflowcx_v3.types.audio_config import SpeechModelVariant +from google.cloud.dialogflowcx_v3.types.audio_config import SsmlVoiceGender +from google.cloud.dialogflowcx_v3.types.deployment import Deployment +from google.cloud.dialogflowcx_v3.types.deployment import GetDeploymentRequest +from google.cloud.dialogflowcx_v3.types.deployment import ListDeploymentsRequest +from google.cloud.dialogflowcx_v3.types.deployment import ListDeploymentsResponse +from google.cloud.dialogflowcx_v3.types.entity_type import CreateEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.entity_type import DeleteEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.entity_type import EntityType +from google.cloud.dialogflowcx_v3.types.entity_type import GetEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.entity_type import ListEntityTypesRequest +from google.cloud.dialogflowcx_v3.types.entity_type import ListEntityTypesResponse +from google.cloud.dialogflowcx_v3.types.entity_type import UpdateEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.environment import ContinuousTestResult +from google.cloud.dialogflowcx_v3.types.environment import CreateEnvironmentRequest +from google.cloud.dialogflowcx_v3.types.environment import DeleteEnvironmentRequest +from google.cloud.dialogflowcx_v3.types.environment import DeployFlowMetadata +from google.cloud.dialogflowcx_v3.types.environment import DeployFlowRequest +from google.cloud.dialogflowcx_v3.types.environment import DeployFlowResponse +from google.cloud.dialogflowcx_v3.types.environment import Environment +from google.cloud.dialogflowcx_v3.types.environment import GetEnvironmentRequest +from google.cloud.dialogflowcx_v3.types.environment import ListContinuousTestResultsRequest +from google.cloud.dialogflowcx_v3.types.environment import ListContinuousTestResultsResponse +from google.cloud.dialogflowcx_v3.types.environment import ListEnvironmentsRequest +from google.cloud.dialogflowcx_v3.types.environment import ListEnvironmentsResponse +from google.cloud.dialogflowcx_v3.types.environment import LookupEnvironmentHistoryRequest +from google.cloud.dialogflowcx_v3.types.environment import LookupEnvironmentHistoryResponse +from google.cloud.dialogflowcx_v3.types.environment import RunContinuousTestMetadata +from google.cloud.dialogflowcx_v3.types.environment import RunContinuousTestRequest +from google.cloud.dialogflowcx_v3.types.environment import RunContinuousTestResponse +from google.cloud.dialogflowcx_v3.types.environment import UpdateEnvironmentRequest +from google.cloud.dialogflowcx_v3.types.experiment import CreateExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import DeleteExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import Experiment +from google.cloud.dialogflowcx_v3.types.experiment import GetExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import ListExperimentsRequest +from google.cloud.dialogflowcx_v3.types.experiment import ListExperimentsResponse +from google.cloud.dialogflowcx_v3.types.experiment import RolloutConfig +from google.cloud.dialogflowcx_v3.types.experiment import RolloutState +from google.cloud.dialogflowcx_v3.types.experiment import StartExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import StopExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import UpdateExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import VariantsHistory +from google.cloud.dialogflowcx_v3.types.experiment import VersionVariants +from google.cloud.dialogflowcx_v3.types.flow import CreateFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import DeleteFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import ExportFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import ExportFlowResponse +from google.cloud.dialogflowcx_v3.types.flow import Flow +from google.cloud.dialogflowcx_v3.types.flow import FlowValidationResult +from google.cloud.dialogflowcx_v3.types.flow import GetFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import GetFlowValidationResultRequest +from google.cloud.dialogflowcx_v3.types.flow import ImportFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import ImportFlowResponse +from google.cloud.dialogflowcx_v3.types.flow import ListFlowsRequest +from google.cloud.dialogflowcx_v3.types.flow import ListFlowsResponse +from google.cloud.dialogflowcx_v3.types.flow import NluSettings +from google.cloud.dialogflowcx_v3.types.flow import TrainFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import UpdateFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import ValidateFlowRequest +from google.cloud.dialogflowcx_v3.types.fulfillment import Fulfillment +from google.cloud.dialogflowcx_v3.types.intent import CreateIntentRequest +from google.cloud.dialogflowcx_v3.types.intent import DeleteIntentRequest +from google.cloud.dialogflowcx_v3.types.intent import GetIntentRequest +from google.cloud.dialogflowcx_v3.types.intent import Intent +from google.cloud.dialogflowcx_v3.types.intent import ListIntentsRequest +from google.cloud.dialogflowcx_v3.types.intent import ListIntentsResponse +from google.cloud.dialogflowcx_v3.types.intent import UpdateIntentRequest +from google.cloud.dialogflowcx_v3.types.intent import IntentView +from google.cloud.dialogflowcx_v3.types.page import CreatePageRequest +from google.cloud.dialogflowcx_v3.types.page import DeletePageRequest +from google.cloud.dialogflowcx_v3.types.page import EventHandler +from google.cloud.dialogflowcx_v3.types.page import Form +from google.cloud.dialogflowcx_v3.types.page import GetPageRequest +from google.cloud.dialogflowcx_v3.types.page import ListPagesRequest +from google.cloud.dialogflowcx_v3.types.page import ListPagesResponse +from google.cloud.dialogflowcx_v3.types.page import Page +from google.cloud.dialogflowcx_v3.types.page import TransitionRoute +from google.cloud.dialogflowcx_v3.types.page import UpdatePageRequest +from google.cloud.dialogflowcx_v3.types.response_message import ResponseMessage +from google.cloud.dialogflowcx_v3.types.security_settings import CreateSecuritySettingsRequest +from google.cloud.dialogflowcx_v3.types.security_settings import DeleteSecuritySettingsRequest +from google.cloud.dialogflowcx_v3.types.security_settings import GetSecuritySettingsRequest +from google.cloud.dialogflowcx_v3.types.security_settings import ListSecuritySettingsRequest +from google.cloud.dialogflowcx_v3.types.security_settings import ListSecuritySettingsResponse +from google.cloud.dialogflowcx_v3.types.security_settings import SecuritySettings +from google.cloud.dialogflowcx_v3.types.security_settings import UpdateSecuritySettingsRequest +from google.cloud.dialogflowcx_v3.types.session import AudioInput +from google.cloud.dialogflowcx_v3.types.session import DetectIntentRequest +from google.cloud.dialogflowcx_v3.types.session import DetectIntentResponse +from google.cloud.dialogflowcx_v3.types.session import DtmfInput +from google.cloud.dialogflowcx_v3.types.session import EventInput +from google.cloud.dialogflowcx_v3.types.session import FulfillIntentRequest +from google.cloud.dialogflowcx_v3.types.session import FulfillIntentResponse +from google.cloud.dialogflowcx_v3.types.session import IntentInput +from google.cloud.dialogflowcx_v3.types.session import Match +from google.cloud.dialogflowcx_v3.types.session import MatchIntentRequest +from google.cloud.dialogflowcx_v3.types.session import MatchIntentResponse +from google.cloud.dialogflowcx_v3.types.session import QueryInput +from google.cloud.dialogflowcx_v3.types.session import QueryParameters +from google.cloud.dialogflowcx_v3.types.session import QueryResult +from google.cloud.dialogflowcx_v3.types.session import SentimentAnalysisResult +from google.cloud.dialogflowcx_v3.types.session import StreamingDetectIntentRequest +from google.cloud.dialogflowcx_v3.types.session import StreamingDetectIntentResponse +from google.cloud.dialogflowcx_v3.types.session import StreamingRecognitionResult +from google.cloud.dialogflowcx_v3.types.session import TextInput +from google.cloud.dialogflowcx_v3.types.session_entity_type import CreateSessionEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.session_entity_type import DeleteSessionEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.session_entity_type import GetSessionEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.session_entity_type import ListSessionEntityTypesRequest +from google.cloud.dialogflowcx_v3.types.session_entity_type import ListSessionEntityTypesResponse +from google.cloud.dialogflowcx_v3.types.session_entity_type import SessionEntityType +from google.cloud.dialogflowcx_v3.types.session_entity_type import UpdateSessionEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.test_case import BatchDeleteTestCasesRequest +from google.cloud.dialogflowcx_v3.types.test_case import BatchRunTestCasesMetadata +from google.cloud.dialogflowcx_v3.types.test_case import BatchRunTestCasesRequest +from google.cloud.dialogflowcx_v3.types.test_case import BatchRunTestCasesResponse +from google.cloud.dialogflowcx_v3.types.test_case import CalculateCoverageRequest +from google.cloud.dialogflowcx_v3.types.test_case import CalculateCoverageResponse +from google.cloud.dialogflowcx_v3.types.test_case import ConversationTurn +from google.cloud.dialogflowcx_v3.types.test_case import CreateTestCaseRequest +from google.cloud.dialogflowcx_v3.types.test_case import ExportTestCasesMetadata +from google.cloud.dialogflowcx_v3.types.test_case import ExportTestCasesRequest +from google.cloud.dialogflowcx_v3.types.test_case import ExportTestCasesResponse +from google.cloud.dialogflowcx_v3.types.test_case import GetTestCaseRequest +from google.cloud.dialogflowcx_v3.types.test_case import GetTestCaseResultRequest +from google.cloud.dialogflowcx_v3.types.test_case import ImportTestCasesMetadata +from google.cloud.dialogflowcx_v3.types.test_case import ImportTestCasesRequest +from google.cloud.dialogflowcx_v3.types.test_case import ImportTestCasesResponse +from google.cloud.dialogflowcx_v3.types.test_case import IntentCoverage +from google.cloud.dialogflowcx_v3.types.test_case import ListTestCaseResultsRequest +from google.cloud.dialogflowcx_v3.types.test_case import ListTestCaseResultsResponse +from google.cloud.dialogflowcx_v3.types.test_case import ListTestCasesRequest +from google.cloud.dialogflowcx_v3.types.test_case import ListTestCasesResponse +from google.cloud.dialogflowcx_v3.types.test_case import RunTestCaseMetadata +from google.cloud.dialogflowcx_v3.types.test_case import RunTestCaseRequest +from google.cloud.dialogflowcx_v3.types.test_case import RunTestCaseResponse +from google.cloud.dialogflowcx_v3.types.test_case import TestCase +from google.cloud.dialogflowcx_v3.types.test_case import TestCaseError +from google.cloud.dialogflowcx_v3.types.test_case import TestCaseResult +from google.cloud.dialogflowcx_v3.types.test_case import TestConfig +from google.cloud.dialogflowcx_v3.types.test_case import TestError +from google.cloud.dialogflowcx_v3.types.test_case import TestRunDifference +from google.cloud.dialogflowcx_v3.types.test_case import TransitionCoverage +from google.cloud.dialogflowcx_v3.types.test_case import TransitionRouteGroupCoverage +from google.cloud.dialogflowcx_v3.types.test_case import UpdateTestCaseRequest +from google.cloud.dialogflowcx_v3.types.test_case import TestResult +from google.cloud.dialogflowcx_v3.types.transition_route_group import CreateTransitionRouteGroupRequest +from google.cloud.dialogflowcx_v3.types.transition_route_group import DeleteTransitionRouteGroupRequest +from google.cloud.dialogflowcx_v3.types.transition_route_group import GetTransitionRouteGroupRequest +from google.cloud.dialogflowcx_v3.types.transition_route_group import ListTransitionRouteGroupsRequest +from google.cloud.dialogflowcx_v3.types.transition_route_group import ListTransitionRouteGroupsResponse +from google.cloud.dialogflowcx_v3.types.transition_route_group import TransitionRouteGroup +from google.cloud.dialogflowcx_v3.types.transition_route_group import UpdateTransitionRouteGroupRequest +from google.cloud.dialogflowcx_v3.types.validation_message import ResourceName +from google.cloud.dialogflowcx_v3.types.validation_message import ValidationMessage +from google.cloud.dialogflowcx_v3.types.version import CreateVersionOperationMetadata +from google.cloud.dialogflowcx_v3.types.version import CreateVersionRequest +from google.cloud.dialogflowcx_v3.types.version import DeleteVersionRequest +from google.cloud.dialogflowcx_v3.types.version import GetVersionRequest +from google.cloud.dialogflowcx_v3.types.version import ListVersionsRequest +from google.cloud.dialogflowcx_v3.types.version import ListVersionsResponse +from google.cloud.dialogflowcx_v3.types.version import LoadVersionRequest +from google.cloud.dialogflowcx_v3.types.version import UpdateVersionRequest +from google.cloud.dialogflowcx_v3.types.version import Version +from google.cloud.dialogflowcx_v3.types.webhook import CreateWebhookRequest +from google.cloud.dialogflowcx_v3.types.webhook import DeleteWebhookRequest +from google.cloud.dialogflowcx_v3.types.webhook import GetWebhookRequest +from google.cloud.dialogflowcx_v3.types.webhook import ListWebhooksRequest +from google.cloud.dialogflowcx_v3.types.webhook import ListWebhooksResponse +from google.cloud.dialogflowcx_v3.types.webhook import PageInfo +from google.cloud.dialogflowcx_v3.types.webhook import SessionInfo +from google.cloud.dialogflowcx_v3.types.webhook import UpdateWebhookRequest +from google.cloud.dialogflowcx_v3.types.webhook import Webhook +from google.cloud.dialogflowcx_v3.types.webhook import WebhookRequest +from google.cloud.dialogflowcx_v3.types.webhook import WebhookResponse + +__all__ = ('AgentsClient', + 'AgentsAsyncClient', + 'DeploymentsClient', + 'DeploymentsAsyncClient', + 'EntityTypesClient', + 'EntityTypesAsyncClient', + 'EnvironmentsClient', + 'EnvironmentsAsyncClient', + 'ExperimentsClient', + 'ExperimentsAsyncClient', + 'FlowsClient', + 'FlowsAsyncClient', + 'IntentsClient', + 'IntentsAsyncClient', + 'PagesClient', + 'PagesAsyncClient', + 'SecuritySettingsServiceClient', + 'SecuritySettingsServiceAsyncClient', + 'SessionEntityTypesClient', + 'SessionEntityTypesAsyncClient', + 'SessionsClient', + 'SessionsAsyncClient', + 'TestCasesClient', + 'TestCasesAsyncClient', + 'TransitionRouteGroupsClient', + 'TransitionRouteGroupsAsyncClient', + 'VersionsClient', + 'VersionsAsyncClient', + 'WebhooksClient', + 'WebhooksAsyncClient', + 'AdvancedSettings', + 'Agent', + 'AgentValidationResult', + 'CreateAgentRequest', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'GetAgentRequest', + 'GetAgentValidationResultRequest', + 'ListAgentsRequest', + 'ListAgentsResponse', + 'RestoreAgentRequest', + 'SpeechToTextSettings', + 'UpdateAgentRequest', + 'ValidateAgentRequest', + 'InputAudioConfig', + 'OutputAudioConfig', + 'SpeechWordInfo', + 'SynthesizeSpeechConfig', + 'VoiceSelectionParams', + 'AudioEncoding', + 'OutputAudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'Deployment', + 'GetDeploymentRequest', + 'ListDeploymentsRequest', + 'ListDeploymentsResponse', + 'CreateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'EntityType', + 'GetEntityTypeRequest', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'UpdateEntityTypeRequest', + 'ContinuousTestResult', + 'CreateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'DeployFlowMetadata', + 'DeployFlowRequest', + 'DeployFlowResponse', + 'Environment', + 'GetEnvironmentRequest', + 'ListContinuousTestResultsRequest', + 'ListContinuousTestResultsResponse', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LookupEnvironmentHistoryRequest', + 'LookupEnvironmentHistoryResponse', + 'RunContinuousTestMetadata', + 'RunContinuousTestRequest', + 'RunContinuousTestResponse', + 'UpdateEnvironmentRequest', + 'CreateExperimentRequest', + 'DeleteExperimentRequest', + 'Experiment', + 'GetExperimentRequest', + 'ListExperimentsRequest', + 'ListExperimentsResponse', + 'RolloutConfig', + 'RolloutState', + 'StartExperimentRequest', + 'StopExperimentRequest', + 'UpdateExperimentRequest', + 'VariantsHistory', + 'VersionVariants', + 'CreateFlowRequest', + 'DeleteFlowRequest', + 'ExportFlowRequest', + 'ExportFlowResponse', + 'Flow', + 'FlowValidationResult', + 'GetFlowRequest', + 'GetFlowValidationResultRequest', + 'ImportFlowRequest', + 'ImportFlowResponse', + 'ListFlowsRequest', + 'ListFlowsResponse', + 'NluSettings', + 'TrainFlowRequest', + 'UpdateFlowRequest', + 'ValidateFlowRequest', + 'Fulfillment', + 'CreateIntentRequest', + 'DeleteIntentRequest', + 'GetIntentRequest', + 'Intent', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'UpdateIntentRequest', + 'IntentView', + 'CreatePageRequest', + 'DeletePageRequest', + 'EventHandler', + 'Form', + 'GetPageRequest', + 'ListPagesRequest', + 'ListPagesResponse', + 'Page', + 'TransitionRoute', + 'UpdatePageRequest', + 'ResponseMessage', + 'CreateSecuritySettingsRequest', + 'DeleteSecuritySettingsRequest', + 'GetSecuritySettingsRequest', + 'ListSecuritySettingsRequest', + 'ListSecuritySettingsResponse', + 'SecuritySettings', + 'UpdateSecuritySettingsRequest', + 'AudioInput', + 'DetectIntentRequest', + 'DetectIntentResponse', + 'DtmfInput', + 'EventInput', + 'FulfillIntentRequest', + 'FulfillIntentResponse', + 'IntentInput', + 'Match', + 'MatchIntentRequest', + 'MatchIntentResponse', + 'QueryInput', + 'QueryParameters', + 'QueryResult', + 'SentimentAnalysisResult', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'TextInput', + 'CreateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + 'GetSessionEntityTypeRequest', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'SessionEntityType', + 'UpdateSessionEntityTypeRequest', + 'BatchDeleteTestCasesRequest', + 'BatchRunTestCasesMetadata', + 'BatchRunTestCasesRequest', + 'BatchRunTestCasesResponse', + 'CalculateCoverageRequest', + 'CalculateCoverageResponse', + 'ConversationTurn', + 'CreateTestCaseRequest', + 'ExportTestCasesMetadata', + 'ExportTestCasesRequest', + 'ExportTestCasesResponse', + 'GetTestCaseRequest', + 'GetTestCaseResultRequest', + 'ImportTestCasesMetadata', + 'ImportTestCasesRequest', + 'ImportTestCasesResponse', + 'IntentCoverage', + 'ListTestCaseResultsRequest', + 'ListTestCaseResultsResponse', + 'ListTestCasesRequest', + 'ListTestCasesResponse', + 'RunTestCaseMetadata', + 'RunTestCaseRequest', + 'RunTestCaseResponse', + 'TestCase', + 'TestCaseError', + 'TestCaseResult', + 'TestConfig', + 'TestError', + 'TestRunDifference', + 'TransitionCoverage', + 'TransitionRouteGroupCoverage', + 'UpdateTestCaseRequest', + 'TestResult', + 'CreateTransitionRouteGroupRequest', + 'DeleteTransitionRouteGroupRequest', + 'GetTransitionRouteGroupRequest', + 'ListTransitionRouteGroupsRequest', + 'ListTransitionRouteGroupsResponse', + 'TransitionRouteGroup', + 'UpdateTransitionRouteGroupRequest', + 'ResourceName', + 'ValidationMessage', + 'CreateVersionOperationMetadata', + 'CreateVersionRequest', + 'DeleteVersionRequest', + 'GetVersionRequest', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'LoadVersionRequest', + 'UpdateVersionRequest', + 'Version', + 'CreateWebhookRequest', + 'DeleteWebhookRequest', + 'GetWebhookRequest', + 'ListWebhooksRequest', + 'ListWebhooksResponse', + 'PageInfo', + 'SessionInfo', + 'UpdateWebhookRequest', + 'Webhook', + 'WebhookRequest', + 'WebhookResponse', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx/py.typed b/owl-bot-staging/v3/google/cloud/dialogflowcx/py.typed new file mode 100644 index 00000000..60fdca49 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dialogflowcx package uses inline types. diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/__init__.py new file mode 100644 index 00000000..41f32c07 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/__init__.py @@ -0,0 +1,476 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.agents import AgentsClient +from .services.agents import AgentsAsyncClient +from .services.deployments import DeploymentsClient +from .services.deployments import DeploymentsAsyncClient +from .services.entity_types import EntityTypesClient +from .services.entity_types import EntityTypesAsyncClient +from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient +from .services.experiments import ExperimentsClient +from .services.experiments import ExperimentsAsyncClient +from .services.flows import FlowsClient +from .services.flows import FlowsAsyncClient +from .services.intents import IntentsClient +from .services.intents import IntentsAsyncClient +from .services.pages import PagesClient +from .services.pages import PagesAsyncClient +from .services.security_settings_service import SecuritySettingsServiceClient +from .services.security_settings_service import SecuritySettingsServiceAsyncClient +from .services.session_entity_types import SessionEntityTypesClient +from .services.session_entity_types import SessionEntityTypesAsyncClient +from .services.sessions import SessionsClient +from .services.sessions import SessionsAsyncClient +from .services.test_cases import TestCasesClient +from .services.test_cases import TestCasesAsyncClient +from .services.transition_route_groups import TransitionRouteGroupsClient +from .services.transition_route_groups import TransitionRouteGroupsAsyncClient +from .services.versions import VersionsClient +from .services.versions import VersionsAsyncClient +from .services.webhooks import WebhooksClient +from .services.webhooks import WebhooksAsyncClient + +from .types.advanced_settings import AdvancedSettings +from .types.agent import Agent +from .types.agent import AgentValidationResult +from .types.agent import CreateAgentRequest +from .types.agent import DeleteAgentRequest +from .types.agent import ExportAgentRequest +from .types.agent import ExportAgentResponse +from .types.agent import GetAgentRequest +from .types.agent import GetAgentValidationResultRequest +from .types.agent import ListAgentsRequest +from .types.agent import ListAgentsResponse +from .types.agent import RestoreAgentRequest +from .types.agent import SpeechToTextSettings +from .types.agent import UpdateAgentRequest +from .types.agent import ValidateAgentRequest +from .types.audio_config import InputAudioConfig +from .types.audio_config import OutputAudioConfig +from .types.audio_config import SpeechWordInfo +from .types.audio_config import SynthesizeSpeechConfig +from .types.audio_config import VoiceSelectionParams +from .types.audio_config import AudioEncoding +from .types.audio_config import OutputAudioEncoding +from .types.audio_config import SpeechModelVariant +from .types.audio_config import SsmlVoiceGender +from .types.deployment import Deployment +from .types.deployment import GetDeploymentRequest +from .types.deployment import ListDeploymentsRequest +from .types.deployment import ListDeploymentsResponse +from .types.entity_type import CreateEntityTypeRequest +from .types.entity_type import DeleteEntityTypeRequest +from .types.entity_type import EntityType +from .types.entity_type import GetEntityTypeRequest +from .types.entity_type import ListEntityTypesRequest +from .types.entity_type import ListEntityTypesResponse +from .types.entity_type import UpdateEntityTypeRequest +from .types.environment import ContinuousTestResult +from .types.environment import CreateEnvironmentRequest +from .types.environment import DeleteEnvironmentRequest +from .types.environment import DeployFlowMetadata +from .types.environment import DeployFlowRequest +from .types.environment import DeployFlowResponse +from .types.environment import Environment +from .types.environment import GetEnvironmentRequest +from .types.environment import ListContinuousTestResultsRequest +from .types.environment import ListContinuousTestResultsResponse +from .types.environment import ListEnvironmentsRequest +from .types.environment import ListEnvironmentsResponse +from .types.environment import LookupEnvironmentHistoryRequest +from .types.environment import LookupEnvironmentHistoryResponse +from .types.environment import RunContinuousTestMetadata +from .types.environment import RunContinuousTestRequest +from .types.environment import RunContinuousTestResponse +from .types.environment import UpdateEnvironmentRequest +from .types.experiment import CreateExperimentRequest +from .types.experiment import DeleteExperimentRequest +from .types.experiment import Experiment +from .types.experiment import GetExperimentRequest +from .types.experiment import ListExperimentsRequest +from .types.experiment import ListExperimentsResponse +from .types.experiment import RolloutConfig +from .types.experiment import RolloutState +from .types.experiment import StartExperimentRequest +from .types.experiment import StopExperimentRequest +from .types.experiment import UpdateExperimentRequest +from .types.experiment import VariantsHistory +from .types.experiment import VersionVariants +from .types.flow import CreateFlowRequest +from .types.flow import DeleteFlowRequest +from .types.flow import ExportFlowRequest +from .types.flow import ExportFlowResponse +from .types.flow import Flow +from .types.flow import FlowValidationResult +from .types.flow import GetFlowRequest +from .types.flow import GetFlowValidationResultRequest +from .types.flow import ImportFlowRequest +from .types.flow import ImportFlowResponse +from .types.flow import ListFlowsRequest +from .types.flow import ListFlowsResponse +from .types.flow import NluSettings +from .types.flow import TrainFlowRequest +from .types.flow import UpdateFlowRequest +from .types.flow import ValidateFlowRequest +from .types.fulfillment import Fulfillment +from .types.intent import CreateIntentRequest +from .types.intent import DeleteIntentRequest +from .types.intent import GetIntentRequest +from .types.intent import Intent +from .types.intent import ListIntentsRequest +from .types.intent import ListIntentsResponse +from .types.intent import UpdateIntentRequest +from .types.intent import IntentView +from .types.page import CreatePageRequest +from .types.page import DeletePageRequest +from .types.page import EventHandler +from .types.page import Form +from .types.page import GetPageRequest +from .types.page import ListPagesRequest +from .types.page import ListPagesResponse +from .types.page import Page +from .types.page import TransitionRoute +from .types.page import UpdatePageRequest +from .types.response_message import ResponseMessage +from .types.security_settings import CreateSecuritySettingsRequest +from .types.security_settings import DeleteSecuritySettingsRequest +from .types.security_settings import GetSecuritySettingsRequest +from .types.security_settings import ListSecuritySettingsRequest +from .types.security_settings import ListSecuritySettingsResponse +from .types.security_settings import SecuritySettings +from .types.security_settings import UpdateSecuritySettingsRequest +from .types.session import AudioInput +from .types.session import DetectIntentRequest +from .types.session import DetectIntentResponse +from .types.session import DtmfInput +from .types.session import EventInput +from .types.session import FulfillIntentRequest +from .types.session import FulfillIntentResponse +from .types.session import IntentInput +from .types.session import Match +from .types.session import MatchIntentRequest +from .types.session import MatchIntentResponse +from .types.session import QueryInput +from .types.session import QueryParameters +from .types.session import QueryResult +from .types.session import SentimentAnalysisResult +from .types.session import StreamingDetectIntentRequest +from .types.session import StreamingDetectIntentResponse +from .types.session import StreamingRecognitionResult +from .types.session import TextInput +from .types.session_entity_type import CreateSessionEntityTypeRequest +from .types.session_entity_type import DeleteSessionEntityTypeRequest +from .types.session_entity_type import GetSessionEntityTypeRequest +from .types.session_entity_type import ListSessionEntityTypesRequest +from .types.session_entity_type import ListSessionEntityTypesResponse +from .types.session_entity_type import SessionEntityType +from .types.session_entity_type import UpdateSessionEntityTypeRequest +from .types.test_case import BatchDeleteTestCasesRequest +from .types.test_case import BatchRunTestCasesMetadata +from .types.test_case import BatchRunTestCasesRequest +from .types.test_case import BatchRunTestCasesResponse +from .types.test_case import CalculateCoverageRequest +from .types.test_case import CalculateCoverageResponse +from .types.test_case import ConversationTurn +from .types.test_case import CreateTestCaseRequest +from .types.test_case import ExportTestCasesMetadata +from .types.test_case import ExportTestCasesRequest +from .types.test_case import ExportTestCasesResponse +from .types.test_case import GetTestCaseRequest +from .types.test_case import GetTestCaseResultRequest +from .types.test_case import ImportTestCasesMetadata +from .types.test_case import ImportTestCasesRequest +from .types.test_case import ImportTestCasesResponse +from .types.test_case import IntentCoverage +from .types.test_case import ListTestCaseResultsRequest +from .types.test_case import ListTestCaseResultsResponse +from .types.test_case import ListTestCasesRequest +from .types.test_case import ListTestCasesResponse +from .types.test_case import RunTestCaseMetadata +from .types.test_case import RunTestCaseRequest +from .types.test_case import RunTestCaseResponse +from .types.test_case import TestCase +from .types.test_case import TestCaseError +from .types.test_case import TestCaseResult +from .types.test_case import TestConfig +from .types.test_case import TestError +from .types.test_case import TestRunDifference +from .types.test_case import TransitionCoverage +from .types.test_case import TransitionRouteGroupCoverage +from .types.test_case import UpdateTestCaseRequest +from .types.test_case import TestResult +from .types.transition_route_group import CreateTransitionRouteGroupRequest +from .types.transition_route_group import DeleteTransitionRouteGroupRequest +from .types.transition_route_group import GetTransitionRouteGroupRequest +from .types.transition_route_group import ListTransitionRouteGroupsRequest +from .types.transition_route_group import ListTransitionRouteGroupsResponse +from .types.transition_route_group import TransitionRouteGroup +from .types.transition_route_group import UpdateTransitionRouteGroupRequest +from .types.validation_message import ResourceName +from .types.validation_message import ValidationMessage +from .types.version import CreateVersionOperationMetadata +from .types.version import CreateVersionRequest +from .types.version import DeleteVersionRequest +from .types.version import GetVersionRequest +from .types.version import ListVersionsRequest +from .types.version import ListVersionsResponse +from .types.version import LoadVersionRequest +from .types.version import UpdateVersionRequest +from .types.version import Version +from .types.webhook import CreateWebhookRequest +from .types.webhook import DeleteWebhookRequest +from .types.webhook import GetWebhookRequest +from .types.webhook import ListWebhooksRequest +from .types.webhook import ListWebhooksResponse +from .types.webhook import PageInfo +from .types.webhook import SessionInfo +from .types.webhook import UpdateWebhookRequest +from .types.webhook import Webhook +from .types.webhook import WebhookRequest +from .types.webhook import WebhookResponse + +__all__ = ( + 'AgentsAsyncClient', + 'DeploymentsAsyncClient', + 'EntityTypesAsyncClient', + 'EnvironmentsAsyncClient', + 'ExperimentsAsyncClient', + 'FlowsAsyncClient', + 'IntentsAsyncClient', + 'PagesAsyncClient', + 'SecuritySettingsServiceAsyncClient', + 'SessionEntityTypesAsyncClient', + 'SessionsAsyncClient', + 'TestCasesAsyncClient', + 'TransitionRouteGroupsAsyncClient', + 'VersionsAsyncClient', + 'WebhooksAsyncClient', +'AdvancedSettings', +'Agent', +'AgentValidationResult', +'AgentsClient', +'AudioEncoding', +'AudioInput', +'BatchDeleteTestCasesRequest', +'BatchRunTestCasesMetadata', +'BatchRunTestCasesRequest', +'BatchRunTestCasesResponse', +'CalculateCoverageRequest', +'CalculateCoverageResponse', +'ContinuousTestResult', +'ConversationTurn', +'CreateAgentRequest', +'CreateEntityTypeRequest', +'CreateEnvironmentRequest', +'CreateExperimentRequest', +'CreateFlowRequest', +'CreateIntentRequest', +'CreatePageRequest', +'CreateSecuritySettingsRequest', +'CreateSessionEntityTypeRequest', +'CreateTestCaseRequest', +'CreateTransitionRouteGroupRequest', +'CreateVersionOperationMetadata', +'CreateVersionRequest', +'CreateWebhookRequest', +'DeleteAgentRequest', +'DeleteEntityTypeRequest', +'DeleteEnvironmentRequest', +'DeleteExperimentRequest', +'DeleteFlowRequest', +'DeleteIntentRequest', +'DeletePageRequest', +'DeleteSecuritySettingsRequest', +'DeleteSessionEntityTypeRequest', +'DeleteTransitionRouteGroupRequest', +'DeleteVersionRequest', +'DeleteWebhookRequest', +'DeployFlowMetadata', +'DeployFlowRequest', +'DeployFlowResponse', +'Deployment', +'DeploymentsClient', +'DetectIntentRequest', +'DetectIntentResponse', +'DtmfInput', +'EntityType', +'EntityTypesClient', +'Environment', +'EnvironmentsClient', +'EventHandler', +'EventInput', +'Experiment', +'ExperimentsClient', +'ExportAgentRequest', +'ExportAgentResponse', +'ExportFlowRequest', +'ExportFlowResponse', +'ExportTestCasesMetadata', +'ExportTestCasesRequest', +'ExportTestCasesResponse', +'Flow', +'FlowValidationResult', +'FlowsClient', +'Form', +'FulfillIntentRequest', +'FulfillIntentResponse', +'Fulfillment', +'GetAgentRequest', +'GetAgentValidationResultRequest', +'GetDeploymentRequest', +'GetEntityTypeRequest', +'GetEnvironmentRequest', +'GetExperimentRequest', +'GetFlowRequest', +'GetFlowValidationResultRequest', +'GetIntentRequest', +'GetPageRequest', +'GetSecuritySettingsRequest', +'GetSessionEntityTypeRequest', +'GetTestCaseRequest', +'GetTestCaseResultRequest', +'GetTransitionRouteGroupRequest', +'GetVersionRequest', +'GetWebhookRequest', +'ImportFlowRequest', +'ImportFlowResponse', +'ImportTestCasesMetadata', +'ImportTestCasesRequest', +'ImportTestCasesResponse', +'InputAudioConfig', +'Intent', +'IntentCoverage', +'IntentInput', +'IntentView', +'IntentsClient', +'ListAgentsRequest', +'ListAgentsResponse', +'ListContinuousTestResultsRequest', +'ListContinuousTestResultsResponse', +'ListDeploymentsRequest', +'ListDeploymentsResponse', +'ListEntityTypesRequest', +'ListEntityTypesResponse', +'ListEnvironmentsRequest', +'ListEnvironmentsResponse', +'ListExperimentsRequest', +'ListExperimentsResponse', +'ListFlowsRequest', +'ListFlowsResponse', +'ListIntentsRequest', +'ListIntentsResponse', +'ListPagesRequest', +'ListPagesResponse', +'ListSecuritySettingsRequest', +'ListSecuritySettingsResponse', +'ListSessionEntityTypesRequest', +'ListSessionEntityTypesResponse', +'ListTestCaseResultsRequest', +'ListTestCaseResultsResponse', +'ListTestCasesRequest', +'ListTestCasesResponse', +'ListTransitionRouteGroupsRequest', +'ListTransitionRouteGroupsResponse', +'ListVersionsRequest', +'ListVersionsResponse', +'ListWebhooksRequest', +'ListWebhooksResponse', +'LoadVersionRequest', +'LookupEnvironmentHistoryRequest', +'LookupEnvironmentHistoryResponse', +'Match', +'MatchIntentRequest', +'MatchIntentResponse', +'NluSettings', +'OutputAudioConfig', +'OutputAudioEncoding', +'Page', +'PageInfo', +'PagesClient', +'QueryInput', +'QueryParameters', +'QueryResult', +'ResourceName', +'ResponseMessage', +'RestoreAgentRequest', +'RolloutConfig', +'RolloutState', +'RunContinuousTestMetadata', +'RunContinuousTestRequest', +'RunContinuousTestResponse', +'RunTestCaseMetadata', +'RunTestCaseRequest', +'RunTestCaseResponse', +'SecuritySettings', +'SecuritySettingsServiceClient', +'SentimentAnalysisResult', +'SessionEntityType', +'SessionEntityTypesClient', +'SessionInfo', +'SessionsClient', +'SpeechModelVariant', +'SpeechToTextSettings', +'SpeechWordInfo', +'SsmlVoiceGender', +'StartExperimentRequest', +'StopExperimentRequest', +'StreamingDetectIntentRequest', +'StreamingDetectIntentResponse', +'StreamingRecognitionResult', +'SynthesizeSpeechConfig', +'TestCase', +'TestCaseError', +'TestCaseResult', +'TestCasesClient', +'TestConfig', +'TestError', +'TestResult', +'TestRunDifference', +'TextInput', +'TrainFlowRequest', +'TransitionCoverage', +'TransitionRoute', +'TransitionRouteGroup', +'TransitionRouteGroupCoverage', +'TransitionRouteGroupsClient', +'UpdateAgentRequest', +'UpdateEntityTypeRequest', +'UpdateEnvironmentRequest', +'UpdateExperimentRequest', +'UpdateFlowRequest', +'UpdateIntentRequest', +'UpdatePageRequest', +'UpdateSecuritySettingsRequest', +'UpdateSessionEntityTypeRequest', +'UpdateTestCaseRequest', +'UpdateTransitionRouteGroupRequest', +'UpdateVersionRequest', +'UpdateWebhookRequest', +'ValidateAgentRequest', +'ValidateFlowRequest', +'ValidationMessage', +'VariantsHistory', +'Version', +'VersionVariants', +'VersionsClient', +'VoiceSelectionParams', +'Webhook', +'WebhookRequest', +'WebhookResponse', +'WebhooksClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/gapic_metadata.json b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/gapic_metadata.json new file mode 100644 index 00000000..49e71efa --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/gapic_metadata.json @@ -0,0 +1,1159 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.dialogflowcx_v3", + "protoPackage": "google.cloud.dialogflow.cx.v3", + "schema": "1.0", + "services": { + "Agents": { + "clients": { + "grpc": { + "libraryClient": "AgentsClient", + "rpcs": { + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetAgentValidationResult": { + "methods": [ + "get_agent_validation_result" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "ValidateAgent": { + "methods": [ + "validate_agent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AgentsAsyncClient", + "rpcs": { + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetAgentValidationResult": { + "methods": [ + "get_agent_validation_result" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "ValidateAgent": { + "methods": [ + "validate_agent" + ] + } + } + } + } + }, + "Deployments": { + "clients": { + "grpc": { + "libraryClient": "DeploymentsClient", + "rpcs": { + "GetDeployment": { + "methods": [ + "get_deployment" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DeploymentsAsyncClient", + "rpcs": { + "GetDeployment": { + "methods": [ + "get_deployment" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EntityTypesAsyncClient", + "rpcs": { + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + } + } + }, + "Environments": { + "clients": { + "grpc": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "DeployFlow": { + "methods": [ + "deploy_flow" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListContinuousTestResults": { + "methods": [ + "list_continuous_test_results" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LookupEnvironmentHistory": { + "methods": [ + "lookup_environment_history" + ] + }, + "RunContinuousTest": { + "methods": [ + "run_continuous_test" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "DeployFlow": { + "methods": [ + "deploy_flow" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListContinuousTestResults": { + "methods": [ + "list_continuous_test_results" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LookupEnvironmentHistory": { + "methods": [ + "lookup_environment_history" + ] + }, + "RunContinuousTest": { + "methods": [ + "run_continuous_test" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "Experiments": { + "clients": { + "grpc": { + "libraryClient": "ExperimentsClient", + "rpcs": { + "CreateExperiment": { + "methods": [ + "create_experiment" + ] + }, + "DeleteExperiment": { + "methods": [ + "delete_experiment" + ] + }, + "GetExperiment": { + "methods": [ + "get_experiment" + ] + }, + "ListExperiments": { + "methods": [ + "list_experiments" + ] + }, + "StartExperiment": { + "methods": [ + "start_experiment" + ] + }, + "StopExperiment": { + "methods": [ + "stop_experiment" + ] + }, + "UpdateExperiment": { + "methods": [ + "update_experiment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ExperimentsAsyncClient", + "rpcs": { + "CreateExperiment": { + "methods": [ + "create_experiment" + ] + }, + "DeleteExperiment": { + "methods": [ + "delete_experiment" + ] + }, + "GetExperiment": { + "methods": [ + "get_experiment" + ] + }, + "ListExperiments": { + "methods": [ + "list_experiments" + ] + }, + "StartExperiment": { + "methods": [ + "start_experiment" + ] + }, + "StopExperiment": { + "methods": [ + "stop_experiment" + ] + }, + "UpdateExperiment": { + "methods": [ + "update_experiment" + ] + } + } + } + } + }, + "Flows": { + "clients": { + "grpc": { + "libraryClient": "FlowsClient", + "rpcs": { + "CreateFlow": { + "methods": [ + "create_flow" + ] + }, + "DeleteFlow": { + "methods": [ + "delete_flow" + ] + }, + "ExportFlow": { + "methods": [ + "export_flow" + ] + }, + "GetFlow": { + "methods": [ + "get_flow" + ] + }, + "GetFlowValidationResult": { + "methods": [ + "get_flow_validation_result" + ] + }, + "ImportFlow": { + "methods": [ + "import_flow" + ] + }, + "ListFlows": { + "methods": [ + "list_flows" + ] + }, + "TrainFlow": { + "methods": [ + "train_flow" + ] + }, + "UpdateFlow": { + "methods": [ + "update_flow" + ] + }, + "ValidateFlow": { + "methods": [ + "validate_flow" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FlowsAsyncClient", + "rpcs": { + "CreateFlow": { + "methods": [ + "create_flow" + ] + }, + "DeleteFlow": { + "methods": [ + "delete_flow" + ] + }, + "ExportFlow": { + "methods": [ + "export_flow" + ] + }, + "GetFlow": { + "methods": [ + "get_flow" + ] + }, + "GetFlowValidationResult": { + "methods": [ + "get_flow_validation_result" + ] + }, + "ImportFlow": { + "methods": [ + "import_flow" + ] + }, + "ListFlows": { + "methods": [ + "list_flows" + ] + }, + "TrainFlow": { + "methods": [ + "train_flow" + ] + }, + "UpdateFlow": { + "methods": [ + "update_flow" + ] + }, + "ValidateFlow": { + "methods": [ + "validate_flow" + ] + } + } + } + } + }, + "Intents": { + "clients": { + "grpc": { + "libraryClient": "IntentsClient", + "rpcs": { + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IntentsAsyncClient", + "rpcs": { + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + } + } + }, + "Pages": { + "clients": { + "grpc": { + "libraryClient": "PagesClient", + "rpcs": { + "CreatePage": { + "methods": [ + "create_page" + ] + }, + "DeletePage": { + "methods": [ + "delete_page" + ] + }, + "GetPage": { + "methods": [ + "get_page" + ] + }, + "ListPages": { + "methods": [ + "list_pages" + ] + }, + "UpdatePage": { + "methods": [ + "update_page" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PagesAsyncClient", + "rpcs": { + "CreatePage": { + "methods": [ + "create_page" + ] + }, + "DeletePage": { + "methods": [ + "delete_page" + ] + }, + "GetPage": { + "methods": [ + "get_page" + ] + }, + "ListPages": { + "methods": [ + "list_pages" + ] + }, + "UpdatePage": { + "methods": [ + "update_page" + ] + } + } + } + } + }, + "SecuritySettingsService": { + "clients": { + "grpc": { + "libraryClient": "SecuritySettingsServiceClient", + "rpcs": { + "CreateSecuritySettings": { + "methods": [ + "create_security_settings" + ] + }, + "DeleteSecuritySettings": { + "methods": [ + "delete_security_settings" + ] + }, + "GetSecuritySettings": { + "methods": [ + "get_security_settings" + ] + }, + "ListSecuritySettings": { + "methods": [ + "list_security_settings" + ] + }, + "UpdateSecuritySettings": { + "methods": [ + "update_security_settings" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecuritySettingsServiceAsyncClient", + "rpcs": { + "CreateSecuritySettings": { + "methods": [ + "create_security_settings" + ] + }, + "DeleteSecuritySettings": { + "methods": [ + "delete_security_settings" + ] + }, + "GetSecuritySettings": { + "methods": [ + "get_security_settings" + ] + }, + "ListSecuritySettings": { + "methods": [ + "list_security_settings" + ] + }, + "UpdateSecuritySettings": { + "methods": [ + "update_security_settings" + ] + } + } + } + } + }, + "SessionEntityTypes": { + "clients": { + "grpc": { + "libraryClient": "SessionEntityTypesClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionEntityTypesAsyncClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + } + } + }, + "Sessions": { + "clients": { + "grpc": { + "libraryClient": "SessionsClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "FulfillIntent": { + "methods": [ + "fulfill_intent" + ] + }, + "MatchIntent": { + "methods": [ + "match_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionsAsyncClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "FulfillIntent": { + "methods": [ + "fulfill_intent" + ] + }, + "MatchIntent": { + "methods": [ + "match_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + } + } + }, + "TestCases": { + "clients": { + "grpc": { + "libraryClient": "TestCasesClient", + "rpcs": { + "BatchDeleteTestCases": { + "methods": [ + "batch_delete_test_cases" + ] + }, + "BatchRunTestCases": { + "methods": [ + "batch_run_test_cases" + ] + }, + "CalculateCoverage": { + "methods": [ + "calculate_coverage" + ] + }, + "CreateTestCase": { + "methods": [ + "create_test_case" + ] + }, + "ExportTestCases": { + "methods": [ + "export_test_cases" + ] + }, + "GetTestCase": { + "methods": [ + "get_test_case" + ] + }, + "GetTestCaseResult": { + "methods": [ + "get_test_case_result" + ] + }, + "ImportTestCases": { + "methods": [ + "import_test_cases" + ] + }, + "ListTestCaseResults": { + "methods": [ + "list_test_case_results" + ] + }, + "ListTestCases": { + "methods": [ + "list_test_cases" + ] + }, + "RunTestCase": { + "methods": [ + "run_test_case" + ] + }, + "UpdateTestCase": { + "methods": [ + "update_test_case" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TestCasesAsyncClient", + "rpcs": { + "BatchDeleteTestCases": { + "methods": [ + "batch_delete_test_cases" + ] + }, + "BatchRunTestCases": { + "methods": [ + "batch_run_test_cases" + ] + }, + "CalculateCoverage": { + "methods": [ + "calculate_coverage" + ] + }, + "CreateTestCase": { + "methods": [ + "create_test_case" + ] + }, + "ExportTestCases": { + "methods": [ + "export_test_cases" + ] + }, + "GetTestCase": { + "methods": [ + "get_test_case" + ] + }, + "GetTestCaseResult": { + "methods": [ + "get_test_case_result" + ] + }, + "ImportTestCases": { + "methods": [ + "import_test_cases" + ] + }, + "ListTestCaseResults": { + "methods": [ + "list_test_case_results" + ] + }, + "ListTestCases": { + "methods": [ + "list_test_cases" + ] + }, + "RunTestCase": { + "methods": [ + "run_test_case" + ] + }, + "UpdateTestCase": { + "methods": [ + "update_test_case" + ] + } + } + } + } + }, + "TransitionRouteGroups": { + "clients": { + "grpc": { + "libraryClient": "TransitionRouteGroupsClient", + "rpcs": { + "CreateTransitionRouteGroup": { + "methods": [ + "create_transition_route_group" + ] + }, + "DeleteTransitionRouteGroup": { + "methods": [ + "delete_transition_route_group" + ] + }, + "GetTransitionRouteGroup": { + "methods": [ + "get_transition_route_group" + ] + }, + "ListTransitionRouteGroups": { + "methods": [ + "list_transition_route_groups" + ] + }, + "UpdateTransitionRouteGroup": { + "methods": [ + "update_transition_route_group" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TransitionRouteGroupsAsyncClient", + "rpcs": { + "CreateTransitionRouteGroup": { + "methods": [ + "create_transition_route_group" + ] + }, + "DeleteTransitionRouteGroup": { + "methods": [ + "delete_transition_route_group" + ] + }, + "GetTransitionRouteGroup": { + "methods": [ + "get_transition_route_group" + ] + }, + "ListTransitionRouteGroups": { + "methods": [ + "list_transition_route_groups" + ] + }, + "UpdateTransitionRouteGroup": { + "methods": [ + "update_transition_route_group" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "LoadVersion": { + "methods": [ + "load_version" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VersionsAsyncClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "LoadVersion": { + "methods": [ + "load_version" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + }, + "Webhooks": { + "clients": { + "grpc": { + "libraryClient": "WebhooksClient", + "rpcs": { + "CreateWebhook": { + "methods": [ + "create_webhook" + ] + }, + "DeleteWebhook": { + "methods": [ + "delete_webhook" + ] + }, + "GetWebhook": { + "methods": [ + "get_webhook" + ] + }, + "ListWebhooks": { + "methods": [ + "list_webhooks" + ] + }, + "UpdateWebhook": { + "methods": [ + "update_webhook" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WebhooksAsyncClient", + "rpcs": { + "CreateWebhook": { + "methods": [ + "create_webhook" + ] + }, + "DeleteWebhook": { + "methods": [ + "delete_webhook" + ] + }, + "GetWebhook": { + "methods": [ + "get_webhook" + ] + }, + "ListWebhooks": { + "methods": [ + "list_webhooks" + ] + }, + "UpdateWebhook": { + "methods": [ + "update_webhook" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/py.typed b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/py.typed new file mode 100644 index 00000000..60fdca49 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dialogflowcx package uses inline types. diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/__init__.py new file mode 100644 index 00000000..057c8b80 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AgentsClient +from .async_client import AgentsAsyncClient + +__all__ = ( + 'AgentsClient', + 'AgentsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/async_client.py new file mode 100644 index 00000000..4477d947 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/async_client.py @@ -0,0 +1,928 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflowcx_v3.services.agents import pagers +from google.cloud.dialogflowcx_v3.types import advanced_settings +from google.cloud.dialogflowcx_v3.types import agent +from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +from google.cloud.dialogflowcx_v3.types import flow +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport +from .client import AgentsClient + + +class AgentsAsyncClient: + """Service for managing [Agents][google.cloud.dialogflow.cx.v3.Agent].""" + + _client: AgentsClient + + DEFAULT_ENDPOINT = AgentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AgentsClient.DEFAULT_MTLS_ENDPOINT + + agent_path = staticmethod(AgentsClient.agent_path) + parse_agent_path = staticmethod(AgentsClient.parse_agent_path) + agent_validation_result_path = staticmethod(AgentsClient.agent_validation_result_path) + parse_agent_validation_result_path = staticmethod(AgentsClient.parse_agent_validation_result_path) + environment_path = staticmethod(AgentsClient.environment_path) + parse_environment_path = staticmethod(AgentsClient.parse_environment_path) + flow_path = staticmethod(AgentsClient.flow_path) + parse_flow_path = staticmethod(AgentsClient.parse_flow_path) + flow_validation_result_path = staticmethod(AgentsClient.flow_validation_result_path) + parse_flow_validation_result_path = staticmethod(AgentsClient.parse_flow_validation_result_path) + security_settings_path = staticmethod(AgentsClient.security_settings_path) + parse_security_settings_path = staticmethod(AgentsClient.parse_security_settings_path) + common_billing_account_path = staticmethod(AgentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AgentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AgentsClient.common_folder_path) + parse_common_folder_path = staticmethod(AgentsClient.parse_common_folder_path) + common_organization_path = staticmethod(AgentsClient.common_organization_path) + parse_common_organization_path = staticmethod(AgentsClient.parse_common_organization_path) + common_project_path = staticmethod(AgentsClient.common_project_path) + parse_common_project_path = staticmethod(AgentsClient.parse_common_project_path) + common_location_path = staticmethod(AgentsClient.common_location_path) + parse_common_location_path = staticmethod(AgentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AgentsAsyncClient: The constructed client. + """ + return AgentsClient.from_service_account_info.__func__(AgentsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AgentsAsyncClient: The constructed client. + """ + return AgentsClient.from_service_account_file.__func__(AgentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AgentsTransport: + """Returns the transport used by the client instance. + + Returns: + AgentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AgentsClient).get_transport_class, type(AgentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, AgentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the agents client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.AgentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AgentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_agents(self, + request: agent.ListAgentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAgentsAsyncPager: + r"""Returns the list of all agents in the specified + location. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListAgentsRequest`): + The request object. The request message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. + parent (:class:`str`): + Required. The location to list all agents for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.agents.pagers.ListAgentsAsyncPager: + The response message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = agent.ListAgentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_agents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAgentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_agent(self, + request: agent.GetAgentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.Agent: + r"""Retrieves the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetAgentRequest`): + The request object. The request message for + [Agents.GetAgent][google.cloud.dialogflow.cx.v3.Agents.GetAgent]. + name (:class:`str`): + Required. The name of the agent. Format: + ``projects//locations//agents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = agent.GetAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_agent(self, + request: gcdc_agent.CreateAgentRequest = None, + *, + parent: str = None, + agent: gcdc_agent.Agent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_agent.Agent: + r"""Creates an agent in the specified location. + + Note: You should always train flows prior to sending them + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateAgentRequest`): + The request object. The request message for + [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent]. + parent (:class:`str`): + Required. The location to create a agent for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent (:class:`google.cloud.dialogflowcx_v3.types.Agent`): + Required. The agent to create. + This corresponds to the ``agent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, agent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_agent.CreateAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if agent is not None: + request.agent = agent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_agent(self, + request: gcdc_agent.UpdateAgentRequest = None, + *, + agent: gcdc_agent.Agent = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_agent.Agent: + r"""Updates the specified agent. + + Note: You should always train flows prior to sending them + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateAgentRequest`): + The request object. The request message for + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent]. + agent (:class:`google.cloud.dialogflowcx_v3.types.Agent`): + Required. The agent to update. + This corresponds to the ``agent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The mask to control which fields get + updated. If the mask is not present, all + fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([agent, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_agent.UpdateAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent is not None: + request.agent = agent + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent.name", request.agent.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_agent(self, + request: agent.DeleteAgentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteAgentRequest`): + The request object. The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3.Agents.DeleteAgent]. + name (:class:`str`): + Required. The name of the agent to delete. Format: + ``projects//locations//agents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = agent.DeleteAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def export_agent(self, + request: agent.ExportAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the specified agent to a binary file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportAgentResponse][google.cloud.dialogflow.cx.v3.ExportAgentResponse] + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ExportAgentRequest`): + The request object. The request message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportAgentResponse` + The response message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. + + """ + # Create or coerce a protobuf request object. + request = agent.ExportAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + agent.ExportAgentResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def restore_agent(self, + request: agent.RestoreAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Restores the specified agent from a binary file. + + Replaces the current agent with a new one. Note that all + existing resources in agent (e.g. intents, entity types, flows) + will be removed. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train flows prior to sending them + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.RestoreAgentRequest`): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + request = agent.RestoreAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.restore_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def validate_agent(self, + request: agent.ValidateAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.AgentValidationResult: + r"""Validates the specified agent and creates or updates + validation results. The agent in draft version is + validated. Please call this API after the training is + completed to get the complete validation results. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ValidateAgentRequest`): + The request object. The request message for + [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3.Agents.ValidateAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.AgentValidationResult: + The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + + """ + # Create or coerce a protobuf request object. + request = agent.ValidateAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.validate_agent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_agent_validation_result(self, + request: agent.GetAgentValidationResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.AgentValidationResult: + r"""Gets the latest agent validation result. Agent + validation is performed when ValidateAgent is called. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetAgentValidationResultRequest`): + The request object. The request message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + name (:class:`str`): + Required. The agent name. Format: + ``projects//locations//agents//validationResult``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.AgentValidationResult: + The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = agent.GetAgentValidationResultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_agent_validation_result, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AgentsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/client.py new file mode 100644 index 00000000..88ea068c --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/client.py @@ -0,0 +1,1173 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflowcx_v3.services.agents import pagers +from google.cloud.dialogflowcx_v3.types import advanced_settings +from google.cloud.dialogflowcx_v3.types import agent +from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +from google.cloud.dialogflowcx_v3.types import flow +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AgentsGrpcTransport +from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport + + +class AgentsClientMeta(type): + """Metaclass for the Agents client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[AgentsTransport]] + _transport_registry["grpc"] = AgentsGrpcTransport + _transport_registry["grpc_asyncio"] = AgentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[AgentsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AgentsClient(metaclass=AgentsClientMeta): + """Service for managing [Agents][google.cloud.dialogflow.cx.v3.Agent].""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AgentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AgentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AgentsTransport: + """Returns the transport used by the client instance. + + Returns: + AgentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def agent_path(project: str,location: str,agent: str,) -> str: + """Returns a fully-qualified agent string.""" + return "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str,str]: + """Parses a agent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def agent_validation_result_path(project: str,location: str,agent: str,) -> str: + """Returns a fully-qualified agent_validation_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/validationResult".format(project=project, location=location, agent=agent, ) + + @staticmethod + def parse_agent_validation_result_path(path: str) -> Dict[str,str]: + """Parses a agent_validation_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/validationResult$", path) + return m.groupdict() if m else {} + + @staticmethod + def environment_path(project: str,location: str,agent: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_validation_result_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow_validation_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_validation_result_path(path: str) -> Dict[str,str]: + """Parses a flow_validation_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_settings_path(project: str,location: str,security_settings: str,) -> str: + """Returns a fully-qualified security_settings string.""" + return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + + @staticmethod + def parse_security_settings_path(path: str) -> Dict[str,str]: + """Parses a security_settings path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AgentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the agents client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, AgentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AgentsTransport): + # transport is a AgentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_agents(self, + request: Union[agent.ListAgentsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAgentsPager: + r"""Returns the list of all agents in the specified + location. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListAgentsRequest, dict]): + The request object. The request message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. + parent (str): + Required. The location to list all agents for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.agents.pagers.ListAgentsPager: + The response message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a agent.ListAgentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ListAgentsRequest): + request = agent.ListAgentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_agents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAgentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_agent(self, + request: Union[agent.GetAgentRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.Agent: + r"""Retrieves the specified agent. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetAgentRequest, dict]): + The request object. The request message for + [Agents.GetAgent][google.cloud.dialogflow.cx.v3.Agents.GetAgent]. + name (str): + Required. The name of the agent. Format: + ``projects//locations//agents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a agent.GetAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.GetAgentRequest): + request = agent.GetAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_agent(self, + request: Union[gcdc_agent.CreateAgentRequest, dict] = None, + *, + parent: str = None, + agent: gcdc_agent.Agent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_agent.Agent: + r"""Creates an agent in the specified location. + + Note: You should always train flows prior to sending them + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateAgentRequest, dict]): + The request object. The request message for + [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent]. + parent (str): + Required. The location to create a agent for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent (google.cloud.dialogflowcx_v3.types.Agent): + Required. The agent to create. + This corresponds to the ``agent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, agent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_agent.CreateAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_agent.CreateAgentRequest): + request = gcdc_agent.CreateAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if agent is not None: + request.agent = agent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_agent(self, + request: Union[gcdc_agent.UpdateAgentRequest, dict] = None, + *, + agent: gcdc_agent.Agent = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_agent.Agent: + r"""Updates the specified agent. + + Note: You should always train flows prior to sending them + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateAgentRequest, dict]): + The request object. The request message for + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent]. + agent (google.cloud.dialogflowcx_v3.types.Agent): + Required. The agent to update. + This corresponds to the ``agent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get + updated. If the mask is not present, all + fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([agent, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_agent.UpdateAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_agent.UpdateAgentRequest): + request = gcdc_agent.UpdateAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent is not None: + request.agent = agent + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent.name", request.agent.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_agent(self, + request: Union[agent.DeleteAgentRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteAgentRequest, dict]): + The request object. The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3.Agents.DeleteAgent]. + name (str): + Required. The name of the agent to delete. Format: + ``projects//locations//agents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a agent.DeleteAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.DeleteAgentRequest): + request = agent.DeleteAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def export_agent(self, + request: Union[agent.ExportAgentRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the specified agent to a binary file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportAgentResponse][google.cloud.dialogflow.cx.v3.ExportAgentResponse] + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ExportAgentRequest, dict]): + The request object. The request message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportAgentResponse` + The response message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.ExportAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ExportAgentRequest): + request = agent.ExportAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + agent.ExportAgentResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def restore_agent(self, + request: Union[agent.RestoreAgentRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Restores the specified agent from a binary file. + + Replaces the current agent with a new one. Note that all + existing resources in agent (e.g. intents, entity types, flows) + will be removed. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train flows prior to sending them + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.RestoreAgentRequest, dict]): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.RestoreAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.RestoreAgentRequest): + request = agent.RestoreAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.restore_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def validate_agent(self, + request: Union[agent.ValidateAgentRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.AgentValidationResult: + r"""Validates the specified agent and creates or updates + validation results. The agent in draft version is + validated. Please call this API after the training is + completed to get the complete validation results. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ValidateAgentRequest, dict]): + The request object. The request message for + [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3.Agents.ValidateAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.AgentValidationResult: + The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.ValidateAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ValidateAgentRequest): + request = agent.ValidateAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_agent_validation_result(self, + request: Union[agent.GetAgentValidationResultRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.AgentValidationResult: + r"""Gets the latest agent validation result. Agent + validation is performed when ValidateAgent is called. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetAgentValidationResultRequest, dict]): + The request object. The request message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + name (str): + Required. The agent name. Format: + ``projects//locations//agents//validationResult``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.AgentValidationResult: + The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a agent.GetAgentValidationResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.GetAgentValidationResultRequest): + request = agent.GetAgentValidationResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_agent_validation_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AgentsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/pagers.py new file mode 100644 index 00000000..3cf2a1d8 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import agent + + +class ListAgentsPager: + """A pager for iterating through ``list_agents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListAgentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``agents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAgents`` requests and continue to iterate + through the ``agents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListAgentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., agent.ListAgentsResponse], + request: agent.ListAgentsRequest, + response: agent.ListAgentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListAgentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListAgentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = agent.ListAgentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent.ListAgentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[agent.Agent]: + for page in self.pages: + yield from page.agents + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAgentsAsyncPager: + """A pager for iterating through ``list_agents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListAgentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``agents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAgents`` requests and continue to iterate + through the ``agents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListAgentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[agent.ListAgentsResponse]], + request: agent.ListAgentsRequest, + response: agent.ListAgentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListAgentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListAgentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = agent.ListAgentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent.ListAgentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[agent.Agent]: + async def async_generator(): + async for page in self.pages: + for response in page.agents: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py new file mode 100644 index 00000000..0dc0c06c --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AgentsTransport +from .grpc import AgentsGrpcTransport +from .grpc_asyncio import AgentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AgentsTransport]] +_transport_registry['grpc'] = AgentsGrpcTransport +_transport_registry['grpc_asyncio'] = AgentsGrpcAsyncIOTransport + +__all__ = ( + 'AgentsTransport', + 'AgentsGrpcTransport', + 'AgentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/base.py new file mode 100644 index 00000000..47a68842 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/base.py @@ -0,0 +1,299 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import agent +from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class AgentsTransport(abc.ABC): + """Abstract transport class for Agents.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_agents: gapic_v1.method.wrap_method( + self.list_agents, + default_timeout=None, + client_info=client_info, + ), + self.get_agent: gapic_v1.method.wrap_method( + self.get_agent, + default_timeout=None, + client_info=client_info, + ), + self.create_agent: gapic_v1.method.wrap_method( + self.create_agent, + default_timeout=None, + client_info=client_info, + ), + self.update_agent: gapic_v1.method.wrap_method( + self.update_agent, + default_timeout=None, + client_info=client_info, + ), + self.delete_agent: gapic_v1.method.wrap_method( + self.delete_agent, + default_timeout=None, + client_info=client_info, + ), + self.export_agent: gapic_v1.method.wrap_method( + self.export_agent, + default_timeout=None, + client_info=client_info, + ), + self.restore_agent: gapic_v1.method.wrap_method( + self.restore_agent, + default_timeout=None, + client_info=client_info, + ), + self.validate_agent: gapic_v1.method.wrap_method( + self.validate_agent, + default_timeout=None, + client_info=client_info, + ), + self.get_agent_validation_result: gapic_v1.method.wrap_method( + self.get_agent_validation_result, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_agents(self) -> Callable[ + [agent.ListAgentsRequest], + Union[ + agent.ListAgentsResponse, + Awaitable[agent.ListAgentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_agent(self) -> Callable[ + [agent.GetAgentRequest], + Union[ + agent.Agent, + Awaitable[agent.Agent] + ]]: + raise NotImplementedError() + + @property + def create_agent(self) -> Callable[ + [gcdc_agent.CreateAgentRequest], + Union[ + gcdc_agent.Agent, + Awaitable[gcdc_agent.Agent] + ]]: + raise NotImplementedError() + + @property + def update_agent(self) -> Callable[ + [gcdc_agent.UpdateAgentRequest], + Union[ + gcdc_agent.Agent, + Awaitable[gcdc_agent.Agent] + ]]: + raise NotImplementedError() + + @property + def delete_agent(self) -> Callable[ + [agent.DeleteAgentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def export_agent(self) -> Callable[ + [agent.ExportAgentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restore_agent(self) -> Callable[ + [agent.RestoreAgentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def validate_agent(self) -> Callable[ + [agent.ValidateAgentRequest], + Union[ + agent.AgentValidationResult, + Awaitable[agent.AgentValidationResult] + ]]: + raise NotImplementedError() + + @property + def get_agent_validation_result(self) -> Callable[ + [agent.GetAgentValidationResultRequest], + Union[ + agent.AgentValidationResult, + Awaitable[agent.AgentValidationResult] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'AgentsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py new file mode 100644 index 00000000..aef08c63 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py @@ -0,0 +1,524 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import agent +from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AgentsTransport, DEFAULT_CLIENT_INFO + + +class AgentsGrpcTransport(AgentsTransport): + """gRPC backend transport for Agents. + + Service for managing [Agents][google.cloud.dialogflow.cx.v3.Agent]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_agents(self) -> Callable[ + [agent.ListAgentsRequest], + agent.ListAgentsResponse]: + r"""Return a callable for the list agents method over gRPC. + + Returns the list of all agents in the specified + location. + + Returns: + Callable[[~.ListAgentsRequest], + ~.ListAgentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_agents' not in self._stubs: + self._stubs['list_agents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/ListAgents', + request_serializer=agent.ListAgentsRequest.serialize, + response_deserializer=agent.ListAgentsResponse.deserialize, + ) + return self._stubs['list_agents'] + + @property + def get_agent(self) -> Callable[ + [agent.GetAgentRequest], + agent.Agent]: + r"""Return a callable for the get agent method over gRPC. + + Retrieves the specified agent. + + Returns: + Callable[[~.GetAgentRequest], + ~.Agent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_agent' not in self._stubs: + self._stubs['get_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/GetAgent', + request_serializer=agent.GetAgentRequest.serialize, + response_deserializer=agent.Agent.deserialize, + ) + return self._stubs['get_agent'] + + @property + def create_agent(self) -> Callable[ + [gcdc_agent.CreateAgentRequest], + gcdc_agent.Agent]: + r"""Return a callable for the create agent method over gRPC. + + Creates an agent in the specified location. + + Note: You should always train flows prior to sending them + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateAgentRequest], + ~.Agent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_agent' not in self._stubs: + self._stubs['create_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/CreateAgent', + request_serializer=gcdc_agent.CreateAgentRequest.serialize, + response_deserializer=gcdc_agent.Agent.deserialize, + ) + return self._stubs['create_agent'] + + @property + def update_agent(self) -> Callable[ + [gcdc_agent.UpdateAgentRequest], + gcdc_agent.Agent]: + r"""Return a callable for the update agent method over gRPC. + + Updates the specified agent. + + Note: You should always train flows prior to sending them + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateAgentRequest], + ~.Agent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_agent' not in self._stubs: + self._stubs['update_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/UpdateAgent', + request_serializer=gcdc_agent.UpdateAgentRequest.serialize, + response_deserializer=gcdc_agent.Agent.deserialize, + ) + return self._stubs['update_agent'] + + @property + def delete_agent(self) -> Callable[ + [agent.DeleteAgentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete agent method over gRPC. + + Deletes the specified agent. + + Returns: + Callable[[~.DeleteAgentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_agent' not in self._stubs: + self._stubs['delete_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/DeleteAgent', + request_serializer=agent.DeleteAgentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_agent'] + + @property + def export_agent(self) -> Callable[ + [agent.ExportAgentRequest], + operations_pb2.Operation]: + r"""Return a callable for the export agent method over gRPC. + + Exports the specified agent to a binary file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportAgentResponse][google.cloud.dialogflow.cx.v3.ExportAgentResponse] + + Returns: + Callable[[~.ExportAgentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_agent' not in self._stubs: + self._stubs['export_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/ExportAgent', + request_serializer=agent.ExportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_agent'] + + @property + def restore_agent(self) -> Callable[ + [agent.RestoreAgentRequest], + operations_pb2.Operation]: + r"""Return a callable for the restore agent method over gRPC. + + Restores the specified agent from a binary file. + + Replaces the current agent with a new one. Note that all + existing resources in agent (e.g. intents, entity types, flows) + will be removed. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train flows prior to sending them + queries. See the `training + documentation `__. + + Returns: + Callable[[~.RestoreAgentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'restore_agent' not in self._stubs: + self._stubs['restore_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/RestoreAgent', + request_serializer=agent.RestoreAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_agent'] + + @property + def validate_agent(self) -> Callable[ + [agent.ValidateAgentRequest], + agent.AgentValidationResult]: + r"""Return a callable for the validate agent method over gRPC. + + Validates the specified agent and creates or updates + validation results. The agent in draft version is + validated. Please call this API after the training is + completed to get the complete validation results. + + Returns: + Callable[[~.ValidateAgentRequest], + ~.AgentValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_agent' not in self._stubs: + self._stubs['validate_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/ValidateAgent', + request_serializer=agent.ValidateAgentRequest.serialize, + response_deserializer=agent.AgentValidationResult.deserialize, + ) + return self._stubs['validate_agent'] + + @property + def get_agent_validation_result(self) -> Callable[ + [agent.GetAgentValidationResultRequest], + agent.AgentValidationResult]: + r"""Return a callable for the get agent validation result method over gRPC. + + Gets the latest agent validation result. Agent + validation is performed when ValidateAgent is called. + + Returns: + Callable[[~.GetAgentValidationResultRequest], + ~.AgentValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_agent_validation_result' not in self._stubs: + self._stubs['get_agent_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/GetAgentValidationResult', + request_serializer=agent.GetAgentValidationResultRequest.serialize, + response_deserializer=agent.AgentValidationResult.deserialize, + ) + return self._stubs['get_agent_validation_result'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'AgentsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py new file mode 100644 index 00000000..6f53da4d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py @@ -0,0 +1,529 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import agent +from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AgentsTransport, DEFAULT_CLIENT_INFO +from .grpc import AgentsGrpcTransport + + +class AgentsGrpcAsyncIOTransport(AgentsTransport): + """gRPC AsyncIO backend transport for Agents. + + Service for managing [Agents][google.cloud.dialogflow.cx.v3.Agent]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_agents(self) -> Callable[ + [agent.ListAgentsRequest], + Awaitable[agent.ListAgentsResponse]]: + r"""Return a callable for the list agents method over gRPC. + + Returns the list of all agents in the specified + location. + + Returns: + Callable[[~.ListAgentsRequest], + Awaitable[~.ListAgentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_agents' not in self._stubs: + self._stubs['list_agents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/ListAgents', + request_serializer=agent.ListAgentsRequest.serialize, + response_deserializer=agent.ListAgentsResponse.deserialize, + ) + return self._stubs['list_agents'] + + @property + def get_agent(self) -> Callable[ + [agent.GetAgentRequest], + Awaitable[agent.Agent]]: + r"""Return a callable for the get agent method over gRPC. + + Retrieves the specified agent. + + Returns: + Callable[[~.GetAgentRequest], + Awaitable[~.Agent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_agent' not in self._stubs: + self._stubs['get_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/GetAgent', + request_serializer=agent.GetAgentRequest.serialize, + response_deserializer=agent.Agent.deserialize, + ) + return self._stubs['get_agent'] + + @property + def create_agent(self) -> Callable[ + [gcdc_agent.CreateAgentRequest], + Awaitable[gcdc_agent.Agent]]: + r"""Return a callable for the create agent method over gRPC. + + Creates an agent in the specified location. + + Note: You should always train flows prior to sending them + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateAgentRequest], + Awaitable[~.Agent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_agent' not in self._stubs: + self._stubs['create_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/CreateAgent', + request_serializer=gcdc_agent.CreateAgentRequest.serialize, + response_deserializer=gcdc_agent.Agent.deserialize, + ) + return self._stubs['create_agent'] + + @property + def update_agent(self) -> Callable[ + [gcdc_agent.UpdateAgentRequest], + Awaitable[gcdc_agent.Agent]]: + r"""Return a callable for the update agent method over gRPC. + + Updates the specified agent. + + Note: You should always train flows prior to sending them + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateAgentRequest], + Awaitable[~.Agent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_agent' not in self._stubs: + self._stubs['update_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/UpdateAgent', + request_serializer=gcdc_agent.UpdateAgentRequest.serialize, + response_deserializer=gcdc_agent.Agent.deserialize, + ) + return self._stubs['update_agent'] + + @property + def delete_agent(self) -> Callable[ + [agent.DeleteAgentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete agent method over gRPC. + + Deletes the specified agent. + + Returns: + Callable[[~.DeleteAgentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_agent' not in self._stubs: + self._stubs['delete_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/DeleteAgent', + request_serializer=agent.DeleteAgentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_agent'] + + @property + def export_agent(self) -> Callable[ + [agent.ExportAgentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export agent method over gRPC. + + Exports the specified agent to a binary file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportAgentResponse][google.cloud.dialogflow.cx.v3.ExportAgentResponse] + + Returns: + Callable[[~.ExportAgentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_agent' not in self._stubs: + self._stubs['export_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/ExportAgent', + request_serializer=agent.ExportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_agent'] + + @property + def restore_agent(self) -> Callable[ + [agent.RestoreAgentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restore agent method over gRPC. + + Restores the specified agent from a binary file. + + Replaces the current agent with a new one. Note that all + existing resources in agent (e.g. intents, entity types, flows) + will be removed. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train flows prior to sending them + queries. See the `training + documentation `__. + + Returns: + Callable[[~.RestoreAgentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'restore_agent' not in self._stubs: + self._stubs['restore_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/RestoreAgent', + request_serializer=agent.RestoreAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_agent'] + + @property + def validate_agent(self) -> Callable[ + [agent.ValidateAgentRequest], + Awaitable[agent.AgentValidationResult]]: + r"""Return a callable for the validate agent method over gRPC. + + Validates the specified agent and creates or updates + validation results. The agent in draft version is + validated. Please call this API after the training is + completed to get the complete validation results. + + Returns: + Callable[[~.ValidateAgentRequest], + Awaitable[~.AgentValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_agent' not in self._stubs: + self._stubs['validate_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/ValidateAgent', + request_serializer=agent.ValidateAgentRequest.serialize, + response_deserializer=agent.AgentValidationResult.deserialize, + ) + return self._stubs['validate_agent'] + + @property + def get_agent_validation_result(self) -> Callable[ + [agent.GetAgentValidationResultRequest], + Awaitable[agent.AgentValidationResult]]: + r"""Return a callable for the get agent validation result method over gRPC. + + Gets the latest agent validation result. Agent + validation is performed when ValidateAgent is called. + + Returns: + Callable[[~.GetAgentValidationResultRequest], + Awaitable[~.AgentValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_agent_validation_result' not in self._stubs: + self._stubs['get_agent_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/GetAgentValidationResult', + request_serializer=agent.GetAgentValidationResultRequest.serialize, + response_deserializer=agent.AgentValidationResult.deserialize, + ) + return self._stubs['get_agent_validation_result'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'AgentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/__init__.py new file mode 100644 index 00000000..79ce84de --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DeploymentsClient +from .async_client import DeploymentsAsyncClient + +__all__ = ( + 'DeploymentsClient', + 'DeploymentsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/async_client.py new file mode 100644 index 00000000..30e3f65a --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/async_client.py @@ -0,0 +1,347 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.deployments import pagers +from google.cloud.dialogflowcx_v3.types import deployment +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DeploymentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DeploymentsGrpcAsyncIOTransport +from .client import DeploymentsClient + + +class DeploymentsAsyncClient: + """Service for managing + [Deployments][google.cloud.dialogflow.cx.v3.Deployment]. + """ + + _client: DeploymentsClient + + DEFAULT_ENDPOINT = DeploymentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DeploymentsClient.DEFAULT_MTLS_ENDPOINT + + deployment_path = staticmethod(DeploymentsClient.deployment_path) + parse_deployment_path = staticmethod(DeploymentsClient.parse_deployment_path) + experiment_path = staticmethod(DeploymentsClient.experiment_path) + parse_experiment_path = staticmethod(DeploymentsClient.parse_experiment_path) + test_case_result_path = staticmethod(DeploymentsClient.test_case_result_path) + parse_test_case_result_path = staticmethod(DeploymentsClient.parse_test_case_result_path) + version_path = staticmethod(DeploymentsClient.version_path) + parse_version_path = staticmethod(DeploymentsClient.parse_version_path) + common_billing_account_path = staticmethod(DeploymentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DeploymentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DeploymentsClient.common_folder_path) + parse_common_folder_path = staticmethod(DeploymentsClient.parse_common_folder_path) + common_organization_path = staticmethod(DeploymentsClient.common_organization_path) + parse_common_organization_path = staticmethod(DeploymentsClient.parse_common_organization_path) + common_project_path = staticmethod(DeploymentsClient.common_project_path) + parse_common_project_path = staticmethod(DeploymentsClient.parse_common_project_path) + common_location_path = staticmethod(DeploymentsClient.common_location_path) + parse_common_location_path = staticmethod(DeploymentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DeploymentsAsyncClient: The constructed client. + """ + return DeploymentsClient.from_service_account_info.__func__(DeploymentsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DeploymentsAsyncClient: The constructed client. + """ + return DeploymentsClient.from_service_account_file.__func__(DeploymentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DeploymentsTransport: + """Returns the transport used by the client instance. + + Returns: + DeploymentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DeploymentsClient).get_transport_class, type(DeploymentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, DeploymentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the deployments client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.DeploymentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DeploymentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_deployments(self, + request: deployment.ListDeploymentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDeploymentsAsyncPager: + r"""Returns the list of all deployments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListDeploymentsRequest`): + The request object. The request message for + [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3.Deployments.ListDeployments]. + parent (:class:`str`): + Required. The + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to list all environments for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.deployments.pagers.ListDeploymentsAsyncPager: + The response message for + [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3.Deployments.ListDeployments]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = deployment.ListDeploymentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_deployments, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDeploymentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_deployment(self, + request: deployment.GetDeploymentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> deployment.Deployment: + r"""Retrieves the specified + [Deployment][google.cloud.dialogflow.cx.v3.Deployment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetDeploymentRequest`): + The request object. The request message for + [Deployments.GetDeployment][google.cloud.dialogflow.cx.v3.Deployments.GetDeployment]. + name (:class:`str`): + Required. The name of the + [Deployment][google.cloud.dialogflow.cx.v3.Deployment]. + Format: + ``projects//locations//agents//environments//deployments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Deployment: + Represents an deployment in an + environment. A deployment happens when a + flow version configured to be active in + the environment. You can configure + running pre-deployment steps, e.g. + running validation test cases, + experiment auto-rollout, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = deployment.GetDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_deployment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DeploymentsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/client.py new file mode 100644 index 00000000..f2e452ee --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/client.py @@ -0,0 +1,571 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.deployments import pagers +from google.cloud.dialogflowcx_v3.types import deployment +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DeploymentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DeploymentsGrpcTransport +from .transports.grpc_asyncio import DeploymentsGrpcAsyncIOTransport + + +class DeploymentsClientMeta(type): + """Metaclass for the Deployments client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[DeploymentsTransport]] + _transport_registry["grpc"] = DeploymentsGrpcTransport + _transport_registry["grpc_asyncio"] = DeploymentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[DeploymentsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class DeploymentsClient(metaclass=DeploymentsClientMeta): + """Service for managing + [Deployments][google.cloud.dialogflow.cx.v3.Deployment]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DeploymentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DeploymentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DeploymentsTransport: + """Returns the transport used by the client instance. + + Returns: + DeploymentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def deployment_path(project: str,location: str,agent: str,environment: str,deployment: str,) -> str: + """Returns a fully-qualified deployment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/deployments/{deployment}".format(project=project, location=location, agent=agent, environment=environment, deployment=deployment, ) + + @staticmethod + def parse_deployment_path(path: str) -> Dict[str,str]: + """Parses a deployment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/deployments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def experiment_path(project: str,location: str,agent: str,environment: str,experiment: str,) -> str: + """Returns a fully-qualified experiment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format(project=project, location=location, agent=agent, environment=environment, experiment=experiment, ) + + @staticmethod + def parse_experiment_path(path: str) -> Dict[str,str]: + """Parses a experiment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/experiments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def test_case_result_path(project: str,location: str,agent: str,test_case: str,result: str,) -> str: + """Returns a fully-qualified test_case_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) + + @staticmethod + def parse_test_case_result_path(path: str) -> Dict[str,str]: + """Parses a test_case_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DeploymentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the deployments client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, DeploymentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DeploymentsTransport): + # transport is a DeploymentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_deployments(self, + request: Union[deployment.ListDeploymentsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDeploymentsPager: + r"""Returns the list of all deployments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListDeploymentsRequest, dict]): + The request object. The request message for + [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3.Deployments.ListDeployments]. + parent (str): + Required. The + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to list all environments for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.deployments.pagers.ListDeploymentsPager: + The response message for + [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3.Deployments.ListDeployments]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a deployment.ListDeploymentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, deployment.ListDeploymentsRequest): + request = deployment.ListDeploymentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_deployments] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDeploymentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_deployment(self, + request: Union[deployment.GetDeploymentRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> deployment.Deployment: + r"""Retrieves the specified + [Deployment][google.cloud.dialogflow.cx.v3.Deployment]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetDeploymentRequest, dict]): + The request object. The request message for + [Deployments.GetDeployment][google.cloud.dialogflow.cx.v3.Deployments.GetDeployment]. + name (str): + Required. The name of the + [Deployment][google.cloud.dialogflow.cx.v3.Deployment]. + Format: + ``projects//locations//agents//environments//deployments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Deployment: + Represents an deployment in an + environment. A deployment happens when a + flow version configured to be active in + the environment. You can configure + running pre-deployment steps, e.g. + running validation test cases, + experiment auto-rollout, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a deployment.GetDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, deployment.GetDeploymentRequest): + request = deployment.GetDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_deployment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DeploymentsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/pagers.py new file mode 100644 index 00000000..7ba134ca --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import deployment + + +class ListDeploymentsPager: + """A pager for iterating through ``list_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListDeploymentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``deployments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDeployments`` requests and continue to iterate + through the ``deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListDeploymentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., deployment.ListDeploymentsResponse], + request: deployment.ListDeploymentsRequest, + response: deployment.ListDeploymentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListDeploymentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListDeploymentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = deployment.ListDeploymentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[deployment.ListDeploymentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[deployment.Deployment]: + for page in self.pages: + yield from page.deployments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDeploymentsAsyncPager: + """A pager for iterating through ``list_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListDeploymentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``deployments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDeployments`` requests and continue to iterate + through the ``deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListDeploymentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[deployment.ListDeploymentsResponse]], + request: deployment.ListDeploymentsRequest, + response: deployment.ListDeploymentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListDeploymentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListDeploymentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = deployment.ListDeploymentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[deployment.ListDeploymentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[deployment.Deployment]: + async def async_generator(): + async for page in self.pages: + for response in page.deployments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/__init__.py new file mode 100644 index 00000000..f42e6f3f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DeploymentsTransport +from .grpc import DeploymentsGrpcTransport +from .grpc_asyncio import DeploymentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DeploymentsTransport]] +_transport_registry['grpc'] = DeploymentsGrpcTransport +_transport_registry['grpc_asyncio'] = DeploymentsGrpcAsyncIOTransport + +__all__ = ( + 'DeploymentsTransport', + 'DeploymentsGrpcTransport', + 'DeploymentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/base.py new file mode 100644 index 00000000..7dd77271 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/base.py @@ -0,0 +1,192 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import deployment + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class DeploymentsTransport(abc.ABC): + """Abstract transport class for Deployments.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_deployments: gapic_v1.method.wrap_method( + self.list_deployments, + default_timeout=None, + client_info=client_info, + ), + self.get_deployment: gapic_v1.method.wrap_method( + self.get_deployment, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_deployments(self) -> Callable[ + [deployment.ListDeploymentsRequest], + Union[ + deployment.ListDeploymentsResponse, + Awaitable[deployment.ListDeploymentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_deployment(self) -> Callable[ + [deployment.GetDeploymentRequest], + Union[ + deployment.Deployment, + Awaitable[deployment.Deployment] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'DeploymentsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/grpc.py new file mode 100644 index 00000000..dbcc8afc --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/grpc.py @@ -0,0 +1,283 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import deployment +from .base import DeploymentsTransport, DEFAULT_CLIENT_INFO + + +class DeploymentsGrpcTransport(DeploymentsTransport): + """gRPC backend transport for Deployments. + + Service for managing + [Deployments][google.cloud.dialogflow.cx.v3.Deployment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_deployments(self) -> Callable[ + [deployment.ListDeploymentsRequest], + deployment.ListDeploymentsResponse]: + r"""Return a callable for the list deployments method over gRPC. + + Returns the list of all deployments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.ListDeploymentsRequest], + ~.ListDeploymentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_deployments' not in self._stubs: + self._stubs['list_deployments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Deployments/ListDeployments', + request_serializer=deployment.ListDeploymentsRequest.serialize, + response_deserializer=deployment.ListDeploymentsResponse.deserialize, + ) + return self._stubs['list_deployments'] + + @property + def get_deployment(self) -> Callable[ + [deployment.GetDeploymentRequest], + deployment.Deployment]: + r"""Return a callable for the get deployment method over gRPC. + + Retrieves the specified + [Deployment][google.cloud.dialogflow.cx.v3.Deployment]. + + Returns: + Callable[[~.GetDeploymentRequest], + ~.Deployment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_deployment' not in self._stubs: + self._stubs['get_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Deployments/GetDeployment', + request_serializer=deployment.GetDeploymentRequest.serialize, + response_deserializer=deployment.Deployment.deserialize, + ) + return self._stubs['get_deployment'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'DeploymentsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/grpc_asyncio.py new file mode 100644 index 00000000..1d909521 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/deployments/transports/grpc_asyncio.py @@ -0,0 +1,288 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import deployment +from .base import DeploymentsTransport, DEFAULT_CLIENT_INFO +from .grpc import DeploymentsGrpcTransport + + +class DeploymentsGrpcAsyncIOTransport(DeploymentsTransport): + """gRPC AsyncIO backend transport for Deployments. + + Service for managing + [Deployments][google.cloud.dialogflow.cx.v3.Deployment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_deployments(self) -> Callable[ + [deployment.ListDeploymentsRequest], + Awaitable[deployment.ListDeploymentsResponse]]: + r"""Return a callable for the list deployments method over gRPC. + + Returns the list of all deployments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.ListDeploymentsRequest], + Awaitable[~.ListDeploymentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_deployments' not in self._stubs: + self._stubs['list_deployments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Deployments/ListDeployments', + request_serializer=deployment.ListDeploymentsRequest.serialize, + response_deserializer=deployment.ListDeploymentsResponse.deserialize, + ) + return self._stubs['list_deployments'] + + @property + def get_deployment(self) -> Callable[ + [deployment.GetDeploymentRequest], + Awaitable[deployment.Deployment]]: + r"""Return a callable for the get deployment method over gRPC. + + Retrieves the specified + [Deployment][google.cloud.dialogflow.cx.v3.Deployment]. + + Returns: + Callable[[~.GetDeploymentRequest], + Awaitable[~.Deployment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_deployment' not in self._stubs: + self._stubs['get_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Deployments/GetDeployment', + request_serializer=deployment.GetDeploymentRequest.serialize, + response_deserializer=deployment.Deployment.deserialize, + ) + return self._stubs['get_deployment'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'DeploymentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py new file mode 100644 index 00000000..82dfe86f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import EntityTypesClient +from .async_client import EntityTypesAsyncClient + +__all__ = ( + 'EntityTypesClient', + 'EntityTypesAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py new file mode 100644 index 00000000..4e01b906 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py @@ -0,0 +1,673 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.entity_types import pagers +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport +from .client import EntityTypesClient + + +class EntityTypesAsyncClient: + """Service for managing + [EntityTypes][google.cloud.dialogflow.cx.v3.EntityType]. + """ + + _client: EntityTypesClient + + DEFAULT_ENDPOINT = EntityTypesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EntityTypesClient.DEFAULT_MTLS_ENDPOINT + + entity_type_path = staticmethod(EntityTypesClient.entity_type_path) + parse_entity_type_path = staticmethod(EntityTypesClient.parse_entity_type_path) + common_billing_account_path = staticmethod(EntityTypesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EntityTypesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EntityTypesClient.common_folder_path) + parse_common_folder_path = staticmethod(EntityTypesClient.parse_common_folder_path) + common_organization_path = staticmethod(EntityTypesClient.common_organization_path) + parse_common_organization_path = staticmethod(EntityTypesClient.parse_common_organization_path) + common_project_path = staticmethod(EntityTypesClient.common_project_path) + parse_common_project_path = staticmethod(EntityTypesClient.parse_common_project_path) + common_location_path = staticmethod(EntityTypesClient.common_location_path) + parse_common_location_path = staticmethod(EntityTypesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EntityTypesAsyncClient: The constructed client. + """ + return EntityTypesClient.from_service_account_info.__func__(EntityTypesAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EntityTypesAsyncClient: The constructed client. + """ + return EntityTypesClient.from_service_account_file.__func__(EntityTypesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> EntityTypesTransport: + """Returns the transport used by the client instance. + + Returns: + EntityTypesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(EntityTypesClient).get_transport_class, type(EntityTypesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, EntityTypesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the entity types client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.EntityTypesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = EntityTypesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_entity_types(self, + request: entity_type.ListEntityTypesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntityTypesAsyncPager: + r"""Returns the list of all entity types in the specified + agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListEntityTypesRequest`): + The request object. The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. + parent (:class:`str`): + Required. The agent to list all entity types for. + Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.entity_types.pagers.ListEntityTypesAsyncPager: + The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = entity_type.ListEntityTypesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_entity_types, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEntityTypesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_entity_type(self, + request: entity_type.GetEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> entity_type.EntityType: + r"""Retrieves the specified entity type. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetEntityTypeRequest`): + The request object. The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.GetEntityType]. + name (:class:`str`): + Required. The name of the entity type. Format: + ``projects//locations//agents//entityTypes/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = entity_type.GetEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_entity_type(self, + request: gcdc_entity_type.CreateEntityTypeRequest = None, + *, + parent: str = None, + entity_type: gcdc_entity_type.EntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateEntityTypeRequest`): + The request object. The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.CreateEntityType]. + parent (:class:`str`): + Required. The agent to create a entity type for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type (:class:`google.cloud.dialogflowcx_v3.types.EntityType`): + Required. The entity type to create. + This corresponds to the ``entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_type]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_entity_type.CreateEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type is not None: + request.entity_type = entity_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_entity_type(self, + request: gcdc_entity_type.UpdateEntityTypeRequest = None, + *, + entity_type: gcdc_entity_type.EntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_entity_type.EntityType: + r"""Updates the specified entity type. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateEntityTypeRequest`): + The request object. The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.UpdateEntityType]. + entity_type (:class:`google.cloud.dialogflowcx_v3.types.EntityType`): + Required. The entity type to update. + This corresponds to the ``entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The mask to control which fields get + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([entity_type, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_entity_type.UpdateEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entity_type is not None: + request.entity_type = entity_type + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entity_type.name", request.entity_type.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_entity_type(self, + request: entity_type.DeleteEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified entity type. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteEntityTypeRequest`): + The request object. The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.DeleteEntityType]. + name (:class:`str`): + Required. The name of the entity type to delete. Format: + ``projects//locations//agents//entityTypes/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = entity_type.DeleteEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EntityTypesAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/client.py new file mode 100644 index 00000000..bbb55921 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/client.py @@ -0,0 +1,870 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.entity_types import pagers +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EntityTypesGrpcTransport +from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport + + +class EntityTypesClientMeta(type): + """Metaclass for the EntityTypes client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[EntityTypesTransport]] + _transport_registry["grpc"] = EntityTypesGrpcTransport + _transport_registry["grpc_asyncio"] = EntityTypesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[EntityTypesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class EntityTypesClient(metaclass=EntityTypesClientMeta): + """Service for managing + [EntityTypes][google.cloud.dialogflow.cx.v3.EntityType]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EntityTypesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EntityTypesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> EntityTypesTransport: + """Returns the transport used by the client instance. + + Returns: + EntityTypesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EntityTypesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the entity types client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, EntityTypesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EntityTypesTransport): + # transport is a EntityTypesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_entity_types(self, + request: Union[entity_type.ListEntityTypesRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEntityTypesPager: + r"""Returns the list of all entity types in the specified + agent. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListEntityTypesRequest, dict]): + The request object. The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. + parent (str): + Required. The agent to list all entity types for. + Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.entity_types.pagers.ListEntityTypesPager: + The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a entity_type.ListEntityTypesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.ListEntityTypesRequest): + request = entity_type.ListEntityTypesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_entity_types] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEntityTypesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_entity_type(self, + request: Union[entity_type.GetEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> entity_type.EntityType: + r"""Retrieves the specified entity type. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.GetEntityType]. + name (str): + Required. The name of the entity type. Format: + ``projects//locations//agents//entityTypes/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a entity_type.GetEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.GetEntityTypeRequest): + request = entity_type.GetEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_entity_type(self, + request: Union[gcdc_entity_type.CreateEntityTypeRequest, dict] = None, + *, + parent: str = None, + entity_type: gcdc_entity_type.EntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.CreateEntityType]. + parent (str): + Required. The agent to create a entity type for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type (google.cloud.dialogflowcx_v3.types.EntityType): + Required. The entity type to create. + This corresponds to the ``entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, entity_type]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_entity_type.CreateEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_entity_type.CreateEntityTypeRequest): + request = gcdc_entity_type.CreateEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type is not None: + request.entity_type = entity_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_entity_type(self, + request: Union[gcdc_entity_type.UpdateEntityTypeRequest, dict] = None, + *, + entity_type: gcdc_entity_type.EntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_entity_type.EntityType: + r"""Updates the specified entity type. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.UpdateEntityType]. + entity_type (google.cloud.dialogflowcx_v3.types.EntityType): + Required. The entity type to update. + This corresponds to the ``entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([entity_type, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_entity_type.UpdateEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_entity_type.UpdateEntityTypeRequest): + request = gcdc_entity_type.UpdateEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entity_type is not None: + request.entity_type = entity_type + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entity_type.name", request.entity_type.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_entity_type(self, + request: Union[entity_type.DeleteEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified entity type. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteEntityTypeRequest, dict]): + The request object. The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.DeleteEntityType]. + name (str): + Required. The name of the entity type to delete. Format: + ``projects//locations//agents//entityTypes/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a entity_type.DeleteEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, entity_type.DeleteEntityTypeRequest): + request = entity_type.DeleteEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EntityTypesClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py new file mode 100644 index 00000000..39d656b6 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import entity_type + + +class ListEntityTypesPager: + """A pager for iterating through ``list_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListEntityTypesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``entity_types`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEntityTypes`` requests and continue to iterate + through the ``entity_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListEntityTypesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., entity_type.ListEntityTypesResponse], + request: entity_type.ListEntityTypesRequest, + response: entity_type.ListEntityTypesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListEntityTypesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = entity_type.ListEntityTypesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[entity_type.ListEntityTypesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[entity_type.EntityType]: + for page in self.pages: + yield from page.entity_types + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEntityTypesAsyncPager: + """A pager for iterating through ``list_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListEntityTypesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``entity_types`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEntityTypes`` requests and continue to iterate + through the ``entity_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListEntityTypesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[entity_type.ListEntityTypesResponse]], + request: entity_type.ListEntityTypesRequest, + response: entity_type.ListEntityTypesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListEntityTypesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = entity_type.ListEntityTypesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[entity_type.ListEntityTypesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[entity_type.EntityType]: + async def async_generator(): + async for page in self.pages: + for response in page.entity_types: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py new file mode 100644 index 00000000..1a2aa82d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import EntityTypesTransport +from .grpc import EntityTypesGrpcTransport +from .grpc_asyncio import EntityTypesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EntityTypesTransport]] +_transport_registry['grpc'] = EntityTypesGrpcTransport +_transport_registry['grpc_asyncio'] = EntityTypesGrpcAsyncIOTransport + +__all__ = ( + 'EntityTypesTransport', + 'EntityTypesGrpcTransport', + 'EntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py new file mode 100644 index 00000000..1fd83571 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class EntityTypesTransport(abc.ABC): + """Abstract transport class for EntityTypes.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_entity_types: gapic_v1.method.wrap_method( + self.list_entity_types, + default_timeout=None, + client_info=client_info, + ), + self.get_entity_type: gapic_v1.method.wrap_method( + self.get_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.create_entity_type: gapic_v1.method.wrap_method( + self.create_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.update_entity_type: gapic_v1.method.wrap_method( + self.update_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.delete_entity_type: gapic_v1.method.wrap_method( + self.delete_entity_type, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_entity_types(self) -> Callable[ + [entity_type.ListEntityTypesRequest], + Union[ + entity_type.ListEntityTypesResponse, + Awaitable[entity_type.ListEntityTypesResponse] + ]]: + raise NotImplementedError() + + @property + def get_entity_type(self) -> Callable[ + [entity_type.GetEntityTypeRequest], + Union[ + entity_type.EntityType, + Awaitable[entity_type.EntityType] + ]]: + raise NotImplementedError() + + @property + def create_entity_type(self) -> Callable[ + [gcdc_entity_type.CreateEntityTypeRequest], + Union[ + gcdc_entity_type.EntityType, + Awaitable[gcdc_entity_type.EntityType] + ]]: + raise NotImplementedError() + + @property + def update_entity_type(self) -> Callable[ + [gcdc_entity_type.UpdateEntityTypeRequest], + Union[ + gcdc_entity_type.EntityType, + Awaitable[gcdc_entity_type.EntityType] + ]]: + raise NotImplementedError() + + @property + def delete_entity_type(self) -> Callable[ + [entity_type.DeleteEntityTypeRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'EntityTypesTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py new file mode 100644 index 00000000..96763544 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py @@ -0,0 +1,374 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type +from google.protobuf import empty_pb2 # type: ignore +from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO + + +class EntityTypesGrpcTransport(EntityTypesTransport): + """gRPC backend transport for EntityTypes. + + Service for managing + [EntityTypes][google.cloud.dialogflow.cx.v3.EntityType]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_entity_types(self) -> Callable[ + [entity_type.ListEntityTypesRequest], + entity_type.ListEntityTypesResponse]: + r"""Return a callable for the list entity types method over gRPC. + + Returns the list of all entity types in the specified + agent. + + Returns: + Callable[[~.ListEntityTypesRequest], + ~.ListEntityTypesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_entity_types' not in self._stubs: + self._stubs['list_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.EntityTypes/ListEntityTypes', + request_serializer=entity_type.ListEntityTypesRequest.serialize, + response_deserializer=entity_type.ListEntityTypesResponse.deserialize, + ) + return self._stubs['list_entity_types'] + + @property + def get_entity_type(self) -> Callable[ + [entity_type.GetEntityTypeRequest], + entity_type.EntityType]: + r"""Return a callable for the get entity type method over gRPC. + + Retrieves the specified entity type. + + Returns: + Callable[[~.GetEntityTypeRequest], + ~.EntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_entity_type' not in self._stubs: + self._stubs['get_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.EntityTypes/GetEntityType', + request_serializer=entity_type.GetEntityTypeRequest.serialize, + response_deserializer=entity_type.EntityType.deserialize, + ) + return self._stubs['get_entity_type'] + + @property + def create_entity_type(self) -> Callable[ + [gcdc_entity_type.CreateEntityTypeRequest], + gcdc_entity_type.EntityType]: + r"""Return a callable for the create entity type method over gRPC. + + Creates an entity type in the specified agent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateEntityTypeRequest], + ~.EntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_entity_type' not in self._stubs: + self._stubs['create_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.EntityTypes/CreateEntityType', + request_serializer=gcdc_entity_type.CreateEntityTypeRequest.serialize, + response_deserializer=gcdc_entity_type.EntityType.deserialize, + ) + return self._stubs['create_entity_type'] + + @property + def update_entity_type(self) -> Callable[ + [gcdc_entity_type.UpdateEntityTypeRequest], + gcdc_entity_type.EntityType]: + r"""Return a callable for the update entity type method over gRPC. + + Updates the specified entity type. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateEntityTypeRequest], + ~.EntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_entity_type' not in self._stubs: + self._stubs['update_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.EntityTypes/UpdateEntityType', + request_serializer=gcdc_entity_type.UpdateEntityTypeRequest.serialize, + response_deserializer=gcdc_entity_type.EntityType.deserialize, + ) + return self._stubs['update_entity_type'] + + @property + def delete_entity_type(self) -> Callable[ + [entity_type.DeleteEntityTypeRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete entity type method over gRPC. + + Deletes the specified entity type. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteEntityTypeRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_entity_type' not in self._stubs: + self._stubs['delete_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.EntityTypes/DeleteEntityType', + request_serializer=entity_type.DeleteEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entity_type'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'EntityTypesGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py new file mode 100644 index 00000000..d7899c74 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py @@ -0,0 +1,379 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type +from google.protobuf import empty_pb2 # type: ignore +from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO +from .grpc import EntityTypesGrpcTransport + + +class EntityTypesGrpcAsyncIOTransport(EntityTypesTransport): + """gRPC AsyncIO backend transport for EntityTypes. + + Service for managing + [EntityTypes][google.cloud.dialogflow.cx.v3.EntityType]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_entity_types(self) -> Callable[ + [entity_type.ListEntityTypesRequest], + Awaitable[entity_type.ListEntityTypesResponse]]: + r"""Return a callable for the list entity types method over gRPC. + + Returns the list of all entity types in the specified + agent. + + Returns: + Callable[[~.ListEntityTypesRequest], + Awaitable[~.ListEntityTypesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_entity_types' not in self._stubs: + self._stubs['list_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.EntityTypes/ListEntityTypes', + request_serializer=entity_type.ListEntityTypesRequest.serialize, + response_deserializer=entity_type.ListEntityTypesResponse.deserialize, + ) + return self._stubs['list_entity_types'] + + @property + def get_entity_type(self) -> Callable[ + [entity_type.GetEntityTypeRequest], + Awaitable[entity_type.EntityType]]: + r"""Return a callable for the get entity type method over gRPC. + + Retrieves the specified entity type. + + Returns: + Callable[[~.GetEntityTypeRequest], + Awaitable[~.EntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_entity_type' not in self._stubs: + self._stubs['get_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.EntityTypes/GetEntityType', + request_serializer=entity_type.GetEntityTypeRequest.serialize, + response_deserializer=entity_type.EntityType.deserialize, + ) + return self._stubs['get_entity_type'] + + @property + def create_entity_type(self) -> Callable[ + [gcdc_entity_type.CreateEntityTypeRequest], + Awaitable[gcdc_entity_type.EntityType]]: + r"""Return a callable for the create entity type method over gRPC. + + Creates an entity type in the specified agent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateEntityTypeRequest], + Awaitable[~.EntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_entity_type' not in self._stubs: + self._stubs['create_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.EntityTypes/CreateEntityType', + request_serializer=gcdc_entity_type.CreateEntityTypeRequest.serialize, + response_deserializer=gcdc_entity_type.EntityType.deserialize, + ) + return self._stubs['create_entity_type'] + + @property + def update_entity_type(self) -> Callable[ + [gcdc_entity_type.UpdateEntityTypeRequest], + Awaitable[gcdc_entity_type.EntityType]]: + r"""Return a callable for the update entity type method over gRPC. + + Updates the specified entity type. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateEntityTypeRequest], + Awaitable[~.EntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_entity_type' not in self._stubs: + self._stubs['update_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.EntityTypes/UpdateEntityType', + request_serializer=gcdc_entity_type.UpdateEntityTypeRequest.serialize, + response_deserializer=gcdc_entity_type.EntityType.deserialize, + ) + return self._stubs['update_entity_type'] + + @property + def delete_entity_type(self) -> Callable[ + [entity_type.DeleteEntityTypeRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete entity type method over gRPC. + + Deletes the specified entity type. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteEntityTypeRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_entity_type' not in self._stubs: + self._stubs['delete_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.EntityTypes/DeleteEntityType', + request_serializer=entity_type.DeleteEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entity_type'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'EntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/__init__.py new file mode 100644 index 00000000..a3ad29ec --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import EnvironmentsClient +from .async_client import EnvironmentsAsyncClient + +__all__ = ( + 'EnvironmentsClient', + 'EnvironmentsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/async_client.py new file mode 100644 index 00000000..ab0e2baa --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/async_client.py @@ -0,0 +1,995 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflowcx_v3.services.environments import pagers +from google.cloud.dialogflowcx_v3.types import environment +from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .client import EnvironmentsClient + + +class EnvironmentsAsyncClient: + """Service for managing + [Environments][google.cloud.dialogflow.cx.v3.Environment]. + """ + + _client: EnvironmentsClient + + DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + + continuous_test_result_path = staticmethod(EnvironmentsClient.continuous_test_result_path) + parse_continuous_test_result_path = staticmethod(EnvironmentsClient.parse_continuous_test_result_path) + environment_path = staticmethod(EnvironmentsClient.environment_path) + parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) + test_case_path = staticmethod(EnvironmentsClient.test_case_path) + parse_test_case_path = staticmethod(EnvironmentsClient.parse_test_case_path) + test_case_result_path = staticmethod(EnvironmentsClient.test_case_result_path) + parse_test_case_result_path = staticmethod(EnvironmentsClient.parse_test_case_result_path) + version_path = staticmethod(EnvironmentsClient.version_path) + parse_version_path = staticmethod(EnvironmentsClient.parse_version_path) + common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) + parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) + common_project_path = staticmethod(EnvironmentsClient.common_project_path) + parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) + common_location_path = staticmethod(EnvironmentsClient.common_location_path) + parse_common_location_path = staticmethod(EnvironmentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> EnvironmentsTransport: + """Returns the transport used by the client instance. + + Returns: + EnvironmentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the environments client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.EnvironmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = EnvironmentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_environments(self, + request: environment.ListEnvironmentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnvironmentsAsyncPager: + r"""Returns the list of all environments in the specified + [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListEnvironmentsRequest`): + The request object. The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to list all + environments for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.environments.pagers.ListEnvironmentsAsyncPager: + The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = environment.ListEnvironmentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_environments, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEnvironmentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_environment(self, + request: environment.GetEnvironmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetEnvironmentRequest`): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3.Environments.GetEnvironment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Environment: + Represents an environment for an + agent. You can create multiple versions + of your agent and publish them to + separate environments. When you edit an + agent, you are editing the draft agent. + At any point, you can save the draft + agent as an agent version, which is an + immutable snapshot of your agent. When + you save the draft agent, it is + published to the default environment. + When you create agent versions, you can + publish them to custom environments. You + can create a variety of custom + environments for testing, development, + production, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = environment.GetEnvironmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_environment(self, + request: gcdc_environment.CreateEnvironmentRequest = None, + *, + parent: str = None, + environment: gcdc_environment.Environment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates an + [Environment][google.cloud.dialogflow.cx.v3.Environment] in the + specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3.Environment] + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateEnvironmentRequest`): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3.Environments.CreateEnvironment]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (:class:`google.cloud.dialogflowcx_v3.types.Environment`): + Required. The environment to create. + This corresponds to the ``environment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.dialogflowcx_v3.types.Environment` Represents an environment for an agent. You can create multiple versions + of your agent and publish them to separate + environments. When you edit an agent, you are editing + the draft agent. At any point, you can save the draft + agent as an agent version, which is an immutable + snapshot of your agent. When you save the draft + agent, it is published to the default environment. + When you create agent versions, you can publish them + to custom environments. You can create a variety of + custom environments for testing, development, + production, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, environment]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_environment.CreateEnvironmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if environment is not None: + request.environment = environment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcdc_environment.Environment, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def update_environment(self, + request: gcdc_environment.UpdateEnvironmentRequest = None, + *, + environment: gcdc_environment.Environment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3.Environment] + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateEnvironmentRequest`): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3.Environments.UpdateEnvironment]. + environment (:class:`google.cloud.dialogflowcx_v3.types.Environment`): + Required. The environment to update. + This corresponds to the ``environment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.dialogflowcx_v3.types.Environment` Represents an environment for an agent. You can create multiple versions + of your agent and publish them to separate + environments. When you edit an agent, you are editing + the draft agent. At any point, you can save the draft + agent as an agent version, which is an immutable + snapshot of your agent. When you save the draft + agent, it is published to the default environment. + When you create agent versions, you can publish them + to custom environments. You can create a variety of + custom environments for testing, development, + production, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([environment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_environment.UpdateEnvironmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if environment is not None: + request.environment = environment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment.name", request.environment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcdc_environment.Environment, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def delete_environment(self, + request: environment.DeleteEnvironmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteEnvironmentRequest`): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3.Environments.DeleteEnvironment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to delete. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = environment.DeleteEnvironmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def lookup_environment_history(self, + request: environment.LookupEnvironmentHistoryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.LookupEnvironmentHistoryAsyncPager: + r"""Looks up the history of the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest`): + The request object. The request message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. + name (:class:`str`): + Required. Resource name of the environment to look up + the history for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.environments.pagers.LookupEnvironmentHistoryAsyncPager: + The response message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = environment.LookupEnvironmentHistoryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.lookup_environment_history, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.LookupEnvironmentHistoryAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_continuous_test(self, + request: environment.RunContinuousTestRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off a continuous test under the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [RunContinuousTestMetadata][google.cloud.dialogflow.cx.v3.RunContinuousTestMetadata] + - ``response``: + [RunContinuousTestResponse][google.cloud.dialogflow.cx.v3.RunContinuousTestResponse] + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.RunContinuousTestRequest`): + The request object. The request message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3.Environments.RunContinuousTest]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.RunContinuousTestResponse` + The response message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3.Environments.RunContinuousTest]. + + """ + # Create or coerce a protobuf request object. + request = environment.RunContinuousTestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.run_continuous_test, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + environment.RunContinuousTestResponse, + metadata_type=environment.RunContinuousTestMetadata, + ) + + # Done; return the response. + return response + + async def list_continuous_test_results(self, + request: environment.ListContinuousTestResultsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContinuousTestResultsAsyncPager: + r"""Fetches a list of continuous test results for a given + environment. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListContinuousTestResultsRequest`): + The request object. The request message for + [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3.Environments.ListContinuousTestResults]. + parent (:class:`str`): + Required. The environment to list results for. Format: + ``projects//locations//agents// environments/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.environments.pagers.ListContinuousTestResultsAsyncPager: + The response message for + [Environments.ListTestCaseResults][]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = environment.ListContinuousTestResultsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_continuous_test_results, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListContinuousTestResultsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def deploy_flow(self, + request: environment.DeployFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deploys a flow to the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [DeployFlowMetadata][google.cloud.dialogflow.cx.v3.DeployFlowMetadata] + - ``response``: + [DeployFlowResponse][google.cloud.dialogflow.cx.v3.DeployFlowResponse] + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeployFlowRequest`): + The request object. The request message for + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3.Environments.DeployFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.DeployFlowResponse` + The response message for + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3.Environments.DeployFlow]. + + """ + # Create or coerce a protobuf request object. + request = environment.DeployFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.deploy_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + environment.DeployFlowResponse, + metadata_type=environment.DeployFlowMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EnvironmentsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/client.py new file mode 100644 index 00000000..63d81ab2 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/client.py @@ -0,0 +1,1230 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflowcx_v3.services.environments import pagers +from google.cloud.dialogflowcx_v3.types import environment +from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EnvironmentsGrpcTransport +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport + + +class EnvironmentsClientMeta(type): + """Metaclass for the Environments client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] + _transport_registry["grpc"] = EnvironmentsGrpcTransport + _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[EnvironmentsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class EnvironmentsClient(metaclass=EnvironmentsClientMeta): + """Service for managing + [Environments][google.cloud.dialogflow.cx.v3.Environment]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EnvironmentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EnvironmentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> EnvironmentsTransport: + """Returns the transport used by the client instance. + + Returns: + EnvironmentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def continuous_test_result_path(project: str,location: str,agent: str,environment: str,continuous_test_result: str,) -> str: + """Returns a fully-qualified continuous_test_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/continuousTestResults/{continuous_test_result}".format(project=project, location=location, agent=agent, environment=environment, continuous_test_result=continuous_test_result, ) + + @staticmethod + def parse_continuous_test_result_path(path: str) -> Dict[str,str]: + """Parses a continuous_test_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/continuousTestResults/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def environment_path(project: str,location: str,agent: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def test_case_path(project: str,location: str,agent: str,test_case: str,) -> str: + """Returns a fully-qualified test_case string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format(project=project, location=location, agent=agent, test_case=test_case, ) + + @staticmethod + def parse_test_case_path(path: str) -> Dict[str,str]: + """Parses a test_case path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def test_case_result_path(project: str,location: str,agent: str,test_case: str,result: str,) -> str: + """Returns a fully-qualified test_case_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) + + @staticmethod + def parse_test_case_result_path(path: str) -> Dict[str,str]: + """Parses a test_case_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EnvironmentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the environments client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, EnvironmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EnvironmentsTransport): + # transport is a EnvironmentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_environments(self, + request: Union[environment.ListEnvironmentsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnvironmentsPager: + r"""Returns the list of all environments in the specified + [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListEnvironmentsRequest, dict]): + The request object. The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to list all + environments for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.environments.pagers.ListEnvironmentsPager: + The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a environment.ListEnvironmentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.ListEnvironmentsRequest): + request = environment.ListEnvironmentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_environments] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEnvironmentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_environment(self, + request: Union[environment.GetEnvironmentRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetEnvironmentRequest, dict]): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3.Environments.GetEnvironment]. + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Environment: + Represents an environment for an + agent. You can create multiple versions + of your agent and publish them to + separate environments. When you edit an + agent, you are editing the draft agent. + At any point, you can save the draft + agent as an agent version, which is an + immutable snapshot of your agent. When + you save the draft agent, it is + published to the default environment. + When you create agent versions, you can + publish them to custom environments. You + can create a variety of custom + environments for testing, development, + production, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentRequest): + request = environment.GetEnvironmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_environment(self, + request: Union[gcdc_environment.CreateEnvironmentRequest, dict] = None, + *, + parent: str = None, + environment: gcdc_environment.Environment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates an + [Environment][google.cloud.dialogflow.cx.v3.Environment] in the + specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3.Environment] + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateEnvironmentRequest, dict]): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3.Environments.CreateEnvironment]. + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (google.cloud.dialogflowcx_v3.types.Environment): + Required. The environment to create. + This corresponds to the ``environment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.dialogflowcx_v3.types.Environment` Represents an environment for an agent. You can create multiple versions + of your agent and publish them to separate + environments. When you edit an agent, you are editing + the draft agent. At any point, you can save the draft + agent as an agent version, which is an immutable + snapshot of your agent. When you save the draft + agent, it is published to the default environment. + When you create agent versions, you can publish them + to custom environments. You can create a variety of + custom environments for testing, development, + production, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, environment]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_environment.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_environment.CreateEnvironmentRequest): + request = gcdc_environment.CreateEnvironmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if environment is not None: + request.environment = environment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcdc_environment.Environment, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def update_environment(self, + request: Union[gcdc_environment.UpdateEnvironmentRequest, dict] = None, + *, + environment: gcdc_environment.Environment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3.Environment] + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateEnvironmentRequest, dict]): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3.Environments.UpdateEnvironment]. + environment (google.cloud.dialogflowcx_v3.types.Environment): + Required. The environment to update. + This corresponds to the ``environment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.dialogflowcx_v3.types.Environment` Represents an environment for an agent. You can create multiple versions + of your agent and publish them to separate + environments. When you edit an agent, you are editing + the draft agent. At any point, you can save the draft + agent as an agent version, which is an immutable + snapshot of your agent. When you save the draft + agent, it is published to the default environment. + When you create agent versions, you can publish them + to custom environments. You can create a variety of + custom environments for testing, development, + production, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([environment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_environment.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_environment.UpdateEnvironmentRequest): + request = gcdc_environment.UpdateEnvironmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if environment is not None: + request.environment = environment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment.name", request.environment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcdc_environment.Environment, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def delete_environment(self, + request: Union[environment.DeleteEnvironmentRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteEnvironmentRequest, dict]): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3.Environments.DeleteEnvironment]. + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to delete. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a environment.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.DeleteEnvironmentRequest): + request = environment.DeleteEnvironmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def lookup_environment_history(self, + request: Union[environment.LookupEnvironmentHistoryRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.LookupEnvironmentHistoryPager: + r"""Looks up the history of the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest, dict]): + The request object. The request message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. + name (str): + Required. Resource name of the environment to look up + the history for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.environments.pagers.LookupEnvironmentHistoryPager: + The response message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a environment.LookupEnvironmentHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.LookupEnvironmentHistoryRequest): + request = environment.LookupEnvironmentHistoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.lookup_environment_history] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.LookupEnvironmentHistoryPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_continuous_test(self, + request: Union[environment.RunContinuousTestRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Kicks off a continuous test under the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [RunContinuousTestMetadata][google.cloud.dialogflow.cx.v3.RunContinuousTestMetadata] + - ``response``: + [RunContinuousTestResponse][google.cloud.dialogflow.cx.v3.RunContinuousTestResponse] + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.RunContinuousTestRequest, dict]): + The request object. The request message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3.Environments.RunContinuousTest]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.RunContinuousTestResponse` + The response message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3.Environments.RunContinuousTest]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.RunContinuousTestRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.RunContinuousTestRequest): + request = environment.RunContinuousTestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_continuous_test] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + environment.RunContinuousTestResponse, + metadata_type=environment.RunContinuousTestMetadata, + ) + + # Done; return the response. + return response + + def list_continuous_test_results(self, + request: Union[environment.ListContinuousTestResultsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContinuousTestResultsPager: + r"""Fetches a list of continuous test results for a given + environment. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListContinuousTestResultsRequest, dict]): + The request object. The request message for + [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3.Environments.ListContinuousTestResults]. + parent (str): + Required. The environment to list results for. Format: + ``projects//locations//agents// environments/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.environments.pagers.ListContinuousTestResultsPager: + The response message for + [Environments.ListTestCaseResults][]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a environment.ListContinuousTestResultsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.ListContinuousTestResultsRequest): + request = environment.ListContinuousTestResultsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_continuous_test_results] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListContinuousTestResultsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def deploy_flow(self, + request: Union[environment.DeployFlowRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deploys a flow to the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [DeployFlowMetadata][google.cloud.dialogflow.cx.v3.DeployFlowMetadata] + - ``response``: + [DeployFlowResponse][google.cloud.dialogflow.cx.v3.DeployFlowResponse] + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeployFlowRequest, dict]): + The request object. The request message for + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3.Environments.DeployFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.DeployFlowResponse` + The response message for + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3.Environments.DeployFlow]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.DeployFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.DeployFlowRequest): + request = environment.DeployFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.deploy_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + environment.DeployFlowResponse, + metadata_type=environment.DeployFlowMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EnvironmentsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/pagers.py new file mode 100644 index 00000000..821d6fb4 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/pagers.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import environment + + +class ListEnvironmentsPager: + """A pager for iterating through ``list_environments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListEnvironmentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEnvironments`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListEnvironmentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., environment.ListEnvironmentsResponse], + request: environment.ListEnvironmentsRequest, + response: environment.ListEnvironmentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListEnvironmentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environment.ListEnvironmentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[environment.ListEnvironmentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[environment.Environment]: + for page in self.pages: + yield from page.environments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEnvironmentsAsyncPager: + """A pager for iterating through ``list_environments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListEnvironmentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEnvironments`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListEnvironmentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[environment.ListEnvironmentsResponse]], + request: environment.ListEnvironmentsRequest, + response: environment.ListEnvironmentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListEnvironmentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environment.ListEnvironmentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[environment.ListEnvironmentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[environment.Environment]: + async def async_generator(): + async for page in self.pages: + for response in page.environments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class LookupEnvironmentHistoryPager: + """A pager for iterating through ``lookup_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse` object, and + provides an ``__iter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``LookupEnvironmentHistory`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., environment.LookupEnvironmentHistoryResponse], + request: environment.LookupEnvironmentHistoryRequest, + response: environment.LookupEnvironmentHistoryResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environment.LookupEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[environment.LookupEnvironmentHistoryResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[environment.Environment]: + for page in self.pages: + yield from page.environments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class LookupEnvironmentHistoryAsyncPager: + """A pager for iterating through ``lookup_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``LookupEnvironmentHistory`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[environment.LookupEnvironmentHistoryResponse]], + request: environment.LookupEnvironmentHistoryRequest, + response: environment.LookupEnvironmentHistoryResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environment.LookupEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[environment.LookupEnvironmentHistoryResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[environment.Environment]: + async def async_generator(): + async for page in self.pages: + for response in page.environments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListContinuousTestResultsPager: + """A pager for iterating through ``list_continuous_test_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListContinuousTestResultsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``continuous_test_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListContinuousTestResults`` requests and continue to iterate + through the ``continuous_test_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListContinuousTestResultsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., environment.ListContinuousTestResultsResponse], + request: environment.ListContinuousTestResultsRequest, + response: environment.ListContinuousTestResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListContinuousTestResultsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListContinuousTestResultsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environment.ListContinuousTestResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[environment.ListContinuousTestResultsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[environment.ContinuousTestResult]: + for page in self.pages: + yield from page.continuous_test_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListContinuousTestResultsAsyncPager: + """A pager for iterating through ``list_continuous_test_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListContinuousTestResultsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``continuous_test_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListContinuousTestResults`` requests and continue to iterate + through the ``continuous_test_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListContinuousTestResultsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[environment.ListContinuousTestResultsResponse]], + request: environment.ListContinuousTestResultsRequest, + response: environment.ListContinuousTestResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListContinuousTestResultsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListContinuousTestResultsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environment.ListContinuousTestResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[environment.ListContinuousTestResultsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[environment.ContinuousTestResult]: + async def async_generator(): + async for page in self.pages: + for response in page.continuous_test_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py new file mode 100644 index 00000000..fac90efe --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import EnvironmentsTransport +from .grpc import EnvironmentsGrpcTransport +from .grpc_asyncio import EnvironmentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] +_transport_registry['grpc'] = EnvironmentsGrpcTransport +_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport + +__all__ = ( + 'EnvironmentsTransport', + 'EnvironmentsGrpcTransport', + 'EnvironmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/base.py new file mode 100644 index 00000000..fd6db980 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/base.py @@ -0,0 +1,299 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import environment +from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class EnvironmentsTransport(abc.ABC): + """Abstract transport class for Environments.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_environments: gapic_v1.method.wrap_method( + self.list_environments, + default_timeout=None, + client_info=client_info, + ), + self.get_environment: gapic_v1.method.wrap_method( + self.get_environment, + default_timeout=None, + client_info=client_info, + ), + self.create_environment: gapic_v1.method.wrap_method( + self.create_environment, + default_timeout=None, + client_info=client_info, + ), + self.update_environment: gapic_v1.method.wrap_method( + self.update_environment, + default_timeout=None, + client_info=client_info, + ), + self.delete_environment: gapic_v1.method.wrap_method( + self.delete_environment, + default_timeout=None, + client_info=client_info, + ), + self.lookup_environment_history: gapic_v1.method.wrap_method( + self.lookup_environment_history, + default_timeout=None, + client_info=client_info, + ), + self.run_continuous_test: gapic_v1.method.wrap_method( + self.run_continuous_test, + default_timeout=None, + client_info=client_info, + ), + self.list_continuous_test_results: gapic_v1.method.wrap_method( + self.list_continuous_test_results, + default_timeout=None, + client_info=client_info, + ), + self.deploy_flow: gapic_v1.method.wrap_method( + self.deploy_flow, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + Union[ + environment.ListEnvironmentsResponse, + Awaitable[environment.ListEnvironmentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_environment(self) -> Callable[ + [environment.GetEnvironmentRequest], + Union[ + environment.Environment, + Awaitable[environment.Environment] + ]]: + raise NotImplementedError() + + @property + def create_environment(self) -> Callable[ + [gcdc_environment.CreateEnvironmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_environment(self) -> Callable[ + [gcdc_environment.UpdateEnvironmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def lookup_environment_history(self) -> Callable[ + [environment.LookupEnvironmentHistoryRequest], + Union[ + environment.LookupEnvironmentHistoryResponse, + Awaitable[environment.LookupEnvironmentHistoryResponse] + ]]: + raise NotImplementedError() + + @property + def run_continuous_test(self) -> Callable[ + [environment.RunContinuousTestRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_continuous_test_results(self) -> Callable[ + [environment.ListContinuousTestResultsRequest], + Union[ + environment.ListContinuousTestResultsResponse, + Awaitable[environment.ListContinuousTestResultsResponse] + ]]: + raise NotImplementedError() + + @property + def deploy_flow(self) -> Callable[ + [environment.DeployFlowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'EnvironmentsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py new file mode 100644 index 00000000..841ded8f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py @@ -0,0 +1,534 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import environment +from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO + + +class EnvironmentsGrpcTransport(EnvironmentsTransport): + """gRPC backend transport for Environments. + + Service for managing + [Environments][google.cloud.dialogflow.cx.v3.Environment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + environment.ListEnvironmentsResponse]: + r"""Return a callable for the list environments method over gRPC. + + Returns the list of all environments in the specified + [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + Returns: + Callable[[~.ListEnvironmentsRequest], + ~.ListEnvironmentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_environments' not in self._stubs: + self._stubs['list_environments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/ListEnvironments', + request_serializer=environment.ListEnvironmentsRequest.serialize, + response_deserializer=environment.ListEnvironmentsResponse.deserialize, + ) + return self._stubs['list_environments'] + + @property + def get_environment(self) -> Callable[ + [environment.GetEnvironmentRequest], + environment.Environment]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.GetEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_environment' not in self._stubs: + self._stubs['get_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/GetEnvironment', + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def create_environment(self) -> Callable[ + [gcdc_environment.CreateEnvironmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the create environment method over gRPC. + + Creates an + [Environment][google.cloud.dialogflow.cx.v3.Environment] in the + specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3.Environment] + + Returns: + Callable[[~.CreateEnvironmentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_environment' not in self._stubs: + self._stubs['create_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/CreateEnvironment', + request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_environment'] + + @property + def update_environment(self) -> Callable[ + [gcdc_environment.UpdateEnvironmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3.Environment] + + Returns: + Callable[[~.UpdateEnvironmentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_environment' not in self._stubs: + self._stubs['update_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/UpdateEnvironment', + request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_environment'] + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_environment' not in self._stubs: + self._stubs['delete_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/DeleteEnvironment', + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_environment'] + + @property + def lookup_environment_history(self) -> Callable[ + [environment.LookupEnvironmentHistoryRequest], + environment.LookupEnvironmentHistoryResponse]: + r"""Return a callable for the lookup environment history method over gRPC. + + Looks up the history of the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.LookupEnvironmentHistoryRequest], + ~.LookupEnvironmentHistoryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'lookup_environment_history' not in self._stubs: + self._stubs['lookup_environment_history'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/LookupEnvironmentHistory', + request_serializer=environment.LookupEnvironmentHistoryRequest.serialize, + response_deserializer=environment.LookupEnvironmentHistoryResponse.deserialize, + ) + return self._stubs['lookup_environment_history'] + + @property + def run_continuous_test(self) -> Callable[ + [environment.RunContinuousTestRequest], + operations_pb2.Operation]: + r"""Return a callable for the run continuous test method over gRPC. + + Kicks off a continuous test under the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [RunContinuousTestMetadata][google.cloud.dialogflow.cx.v3.RunContinuousTestMetadata] + - ``response``: + [RunContinuousTestResponse][google.cloud.dialogflow.cx.v3.RunContinuousTestResponse] + + Returns: + Callable[[~.RunContinuousTestRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_continuous_test' not in self._stubs: + self._stubs['run_continuous_test'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/RunContinuousTest', + request_serializer=environment.RunContinuousTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_continuous_test'] + + @property + def list_continuous_test_results(self) -> Callable[ + [environment.ListContinuousTestResultsRequest], + environment.ListContinuousTestResultsResponse]: + r"""Return a callable for the list continuous test results method over gRPC. + + Fetches a list of continuous test results for a given + environment. + + Returns: + Callable[[~.ListContinuousTestResultsRequest], + ~.ListContinuousTestResultsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_continuous_test_results' not in self._stubs: + self._stubs['list_continuous_test_results'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/ListContinuousTestResults', + request_serializer=environment.ListContinuousTestResultsRequest.serialize, + response_deserializer=environment.ListContinuousTestResultsResponse.deserialize, + ) + return self._stubs['list_continuous_test_results'] + + @property + def deploy_flow(self) -> Callable[ + [environment.DeployFlowRequest], + operations_pb2.Operation]: + r"""Return a callable for the deploy flow method over gRPC. + + Deploys a flow to the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [DeployFlowMetadata][google.cloud.dialogflow.cx.v3.DeployFlowMetadata] + - ``response``: + [DeployFlowResponse][google.cloud.dialogflow.cx.v3.DeployFlowResponse] + + Returns: + Callable[[~.DeployFlowRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'deploy_flow' not in self._stubs: + self._stubs['deploy_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/DeployFlow', + request_serializer=environment.DeployFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['deploy_flow'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'EnvironmentsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py new file mode 100644 index 00000000..8c09731d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py @@ -0,0 +1,539 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import environment +from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import EnvironmentsGrpcTransport + + +class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): + """gRPC AsyncIO backend transport for Environments. + + Service for managing + [Environments][google.cloud.dialogflow.cx.v3.Environment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + Awaitable[environment.ListEnvironmentsResponse]]: + r"""Return a callable for the list environments method over gRPC. + + Returns the list of all environments in the specified + [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + Returns: + Callable[[~.ListEnvironmentsRequest], + Awaitable[~.ListEnvironmentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_environments' not in self._stubs: + self._stubs['list_environments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/ListEnvironments', + request_serializer=environment.ListEnvironmentsRequest.serialize, + response_deserializer=environment.ListEnvironmentsResponse.deserialize, + ) + return self._stubs['list_environments'] + + @property + def get_environment(self) -> Callable[ + [environment.GetEnvironmentRequest], + Awaitable[environment.Environment]]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.GetEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_environment' not in self._stubs: + self._stubs['get_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/GetEnvironment', + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def create_environment(self) -> Callable[ + [gcdc_environment.CreateEnvironmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create environment method over gRPC. + + Creates an + [Environment][google.cloud.dialogflow.cx.v3.Environment] in the + specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3.Environment] + + Returns: + Callable[[~.CreateEnvironmentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_environment' not in self._stubs: + self._stubs['create_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/CreateEnvironment', + request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_environment'] + + @property + def update_environment(self) -> Callable[ + [gcdc_environment.UpdateEnvironmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [Environment][google.cloud.dialogflow.cx.v3.Environment] + + Returns: + Callable[[~.UpdateEnvironmentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_environment' not in self._stubs: + self._stubs['update_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/UpdateEnvironment', + request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_environment'] + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_environment' not in self._stubs: + self._stubs['delete_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/DeleteEnvironment', + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_environment'] + + @property + def lookup_environment_history(self) -> Callable[ + [environment.LookupEnvironmentHistoryRequest], + Awaitable[environment.LookupEnvironmentHistoryResponse]]: + r"""Return a callable for the lookup environment history method over gRPC. + + Looks up the history of the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.LookupEnvironmentHistoryRequest], + Awaitable[~.LookupEnvironmentHistoryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'lookup_environment_history' not in self._stubs: + self._stubs['lookup_environment_history'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/LookupEnvironmentHistory', + request_serializer=environment.LookupEnvironmentHistoryRequest.serialize, + response_deserializer=environment.LookupEnvironmentHistoryResponse.deserialize, + ) + return self._stubs['lookup_environment_history'] + + @property + def run_continuous_test(self) -> Callable[ + [environment.RunContinuousTestRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run continuous test method over gRPC. + + Kicks off a continuous test under the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [RunContinuousTestMetadata][google.cloud.dialogflow.cx.v3.RunContinuousTestMetadata] + - ``response``: + [RunContinuousTestResponse][google.cloud.dialogflow.cx.v3.RunContinuousTestResponse] + + Returns: + Callable[[~.RunContinuousTestRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_continuous_test' not in self._stubs: + self._stubs['run_continuous_test'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/RunContinuousTest', + request_serializer=environment.RunContinuousTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_continuous_test'] + + @property + def list_continuous_test_results(self) -> Callable[ + [environment.ListContinuousTestResultsRequest], + Awaitable[environment.ListContinuousTestResultsResponse]]: + r"""Return a callable for the list continuous test results method over gRPC. + + Fetches a list of continuous test results for a given + environment. + + Returns: + Callable[[~.ListContinuousTestResultsRequest], + Awaitable[~.ListContinuousTestResultsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_continuous_test_results' not in self._stubs: + self._stubs['list_continuous_test_results'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/ListContinuousTestResults', + request_serializer=environment.ListContinuousTestResultsRequest.serialize, + response_deserializer=environment.ListContinuousTestResultsResponse.deserialize, + ) + return self._stubs['list_continuous_test_results'] + + @property + def deploy_flow(self) -> Callable[ + [environment.DeployFlowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the deploy flow method over gRPC. + + Deploys a flow to the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [DeployFlowMetadata][google.cloud.dialogflow.cx.v3.DeployFlowMetadata] + - ``response``: + [DeployFlowResponse][google.cloud.dialogflow.cx.v3.DeployFlowResponse] + + Returns: + Callable[[~.DeployFlowRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'deploy_flow' not in self._stubs: + self._stubs['deploy_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/DeployFlow', + request_serializer=environment.DeployFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['deploy_flow'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'EnvironmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/__init__.py new file mode 100644 index 00000000..6d4dd817 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ExperimentsClient +from .async_client import ExperimentsAsyncClient + +__all__ = ( + 'ExperimentsClient', + 'ExperimentsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/async_client.py new file mode 100644 index 00000000..8d750c75 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/async_client.py @@ -0,0 +1,740 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.experiments import pagers +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport +from .client import ExperimentsClient + + +class ExperimentsAsyncClient: + """Service for managing + [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. + """ + + _client: ExperimentsClient + + DEFAULT_ENDPOINT = ExperimentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ExperimentsClient.DEFAULT_MTLS_ENDPOINT + + experiment_path = staticmethod(ExperimentsClient.experiment_path) + parse_experiment_path = staticmethod(ExperimentsClient.parse_experiment_path) + version_path = staticmethod(ExperimentsClient.version_path) + parse_version_path = staticmethod(ExperimentsClient.parse_version_path) + common_billing_account_path = staticmethod(ExperimentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ExperimentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ExperimentsClient.common_folder_path) + parse_common_folder_path = staticmethod(ExperimentsClient.parse_common_folder_path) + common_organization_path = staticmethod(ExperimentsClient.common_organization_path) + parse_common_organization_path = staticmethod(ExperimentsClient.parse_common_organization_path) + common_project_path = staticmethod(ExperimentsClient.common_project_path) + parse_common_project_path = staticmethod(ExperimentsClient.parse_common_project_path) + common_location_path = staticmethod(ExperimentsClient.common_location_path) + parse_common_location_path = staticmethod(ExperimentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ExperimentsAsyncClient: The constructed client. + """ + return ExperimentsClient.from_service_account_info.__func__(ExperimentsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ExperimentsAsyncClient: The constructed client. + """ + return ExperimentsClient.from_service_account_file.__func__(ExperimentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ExperimentsTransport: + """Returns the transport used by the client instance. + + Returns: + ExperimentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ExperimentsClient).get_transport_class, type(ExperimentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ExperimentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the experiments client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ExperimentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ExperimentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_experiments(self, + request: experiment.ListExperimentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExperimentsAsyncPager: + r"""Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListExperimentsRequest`): + The request object. The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + parent (:class:`str`): + Required. The + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to list all environments for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.experiments.pagers.ListExperimentsAsyncPager: + The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = experiment.ListExperimentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_experiments, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListExperimentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_experiment(self, + request: experiment.GetExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetExperimentRequest`): + The request object. The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = experiment.GetExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_experiment(self, + request: gcdc_experiment.CreateExperimentRequest = None, + *, + parent: str = None, + experiment: gcdc_experiment.Experiment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Creates an + [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the + specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateExperimentRequest`): + The request object. The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + experiment (:class:`google.cloud.dialogflowcx_v3.types.Experiment`): + Required. The experiment to create. + This corresponds to the ``experiment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, experiment]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_experiment.CreateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if experiment is not None: + request.experiment = experiment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_experiment(self, + request: gcdc_experiment.UpdateExperimentRequest = None, + *, + experiment: gcdc_experiment.Experiment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateExperimentRequest`): + The request object. The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. + experiment (:class:`google.cloud.dialogflowcx_v3.types.Experiment`): + Required. The experiment to update. + This corresponds to the ``experiment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([experiment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_experiment.UpdateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if experiment is not None: + request.experiment = experiment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("experiment.name", request.experiment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_experiment(self, + request: experiment.DeleteExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteExperimentRequest`): + The request object. The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to delete. Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = experiment.DeleteExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def start_experiment(self, + request: experiment.StartExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from PENDING to RUNNING. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.StartExperimentRequest`): + The request object. The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to start. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = experiment.StartExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.start_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def stop_experiment(self, + request: experiment.StopExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from RUNNING to DONE. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.StopExperimentRequest`): + The request object. The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to stop. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = experiment.StopExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.stop_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ExperimentsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/client.py new file mode 100644 index 00000000..66619219 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/client.py @@ -0,0 +1,946 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.experiments import pagers +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ExperimentsGrpcTransport +from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport + + +class ExperimentsClientMeta(type): + """Metaclass for the Experiments client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[ExperimentsTransport]] + _transport_registry["grpc"] = ExperimentsGrpcTransport + _transport_registry["grpc_asyncio"] = ExperimentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ExperimentsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ExperimentsClient(metaclass=ExperimentsClientMeta): + """Service for managing + [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ExperimentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ExperimentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ExperimentsTransport: + """Returns the transport used by the client instance. + + Returns: + ExperimentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def experiment_path(project: str,location: str,agent: str,environment: str,experiment: str,) -> str: + """Returns a fully-qualified experiment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format(project=project, location=location, agent=agent, environment=environment, experiment=experiment, ) + + @staticmethod + def parse_experiment_path(path: str) -> Dict[str,str]: + """Parses a experiment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/experiments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ExperimentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the experiments client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ExperimentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ExperimentsTransport): + # transport is a ExperimentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_experiments(self, + request: Union[experiment.ListExperimentsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExperimentsPager: + r"""Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListExperimentsRequest, dict]): + The request object. The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + parent (str): + Required. The + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to list all environments for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.experiments.pagers.ListExperimentsPager: + The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a experiment.ListExperimentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.ListExperimentsRequest): + request = experiment.ListExperimentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_experiments] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListExperimentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_experiment(self, + request: Union[experiment.GetExperimentRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetExperimentRequest, dict]): + The request object. The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a experiment.GetExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.GetExperimentRequest): + request = experiment.GetExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_experiment(self, + request: Union[gcdc_experiment.CreateExperimentRequest, dict] = None, + *, + parent: str = None, + experiment: gcdc_experiment.Experiment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Creates an + [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the + specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateExperimentRequest, dict]): + The request object. The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + experiment (google.cloud.dialogflowcx_v3.types.Experiment): + Required. The experiment to create. + This corresponds to the ``experiment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, experiment]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_experiment.CreateExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_experiment.CreateExperimentRequest): + request = gcdc_experiment.CreateExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if experiment is not None: + request.experiment = experiment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_experiment(self, + request: Union[gcdc_experiment.UpdateExperimentRequest, dict] = None, + *, + experiment: gcdc_experiment.Experiment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateExperimentRequest, dict]): + The request object. The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. + experiment (google.cloud.dialogflowcx_v3.types.Experiment): + Required. The experiment to update. + This corresponds to the ``experiment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([experiment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_experiment.UpdateExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_experiment.UpdateExperimentRequest): + request = gcdc_experiment.UpdateExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if experiment is not None: + request.experiment = experiment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("experiment.name", request.experiment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_experiment(self, + request: Union[experiment.DeleteExperimentRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteExperimentRequest, dict]): + The request object. The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to delete. Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a experiment.DeleteExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.DeleteExperimentRequest): + request = experiment.DeleteExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def start_experiment(self, + request: Union[experiment.StartExperimentRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from PENDING to RUNNING. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.StartExperimentRequest, dict]): + The request object. The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. + name (str): + Required. Resource name of the experiment to start. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a experiment.StartExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.StartExperimentRequest): + request = experiment.StartExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.start_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def stop_experiment(self, + request: Union[experiment.StopExperimentRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from RUNNING to DONE. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.StopExperimentRequest, dict]): + The request object. The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. + name (str): + Required. Resource name of the experiment to stop. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a experiment.StopExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.StopExperimentRequest): + request = experiment.StopExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.stop_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ExperimentsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/pagers.py new file mode 100644 index 00000000..f4b95906 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import experiment + + +class ListExperimentsPager: + """A pager for iterating through ``list_experiments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListExperimentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``experiments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExperiments`` requests and continue to iterate + through the ``experiments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListExperimentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., experiment.ListExperimentsResponse], + request: experiment.ListExperimentsRequest, + response: experiment.ListExperimentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListExperimentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListExperimentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = experiment.ListExperimentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[experiment.ListExperimentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[experiment.Experiment]: + for page in self.pages: + yield from page.experiments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListExperimentsAsyncPager: + """A pager for iterating through ``list_experiments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListExperimentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``experiments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExperiments`` requests and continue to iterate + through the ``experiments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListExperimentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[experiment.ListExperimentsResponse]], + request: experiment.ListExperimentsRequest, + response: experiment.ListExperimentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListExperimentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListExperimentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = experiment.ListExperimentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[experiment.ListExperimentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[experiment.Experiment]: + async def async_generator(): + async for page in self.pages: + for response in page.experiments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py new file mode 100644 index 00000000..80f4c26e --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ExperimentsTransport +from .grpc import ExperimentsGrpcTransport +from .grpc_asyncio import ExperimentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ExperimentsTransport]] +_transport_registry['grpc'] = ExperimentsGrpcTransport +_transport_registry['grpc_asyncio'] = ExperimentsGrpcAsyncIOTransport + +__all__ = ( + 'ExperimentsTransport', + 'ExperimentsGrpcTransport', + 'ExperimentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py new file mode 100644 index 00000000..9f8fb4a8 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py @@ -0,0 +1,264 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class ExperimentsTransport(abc.ABC): + """Abstract transport class for Experiments.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_experiments: gapic_v1.method.wrap_method( + self.list_experiments, + default_timeout=None, + client_info=client_info, + ), + self.get_experiment: gapic_v1.method.wrap_method( + self.get_experiment, + default_timeout=None, + client_info=client_info, + ), + self.create_experiment: gapic_v1.method.wrap_method( + self.create_experiment, + default_timeout=None, + client_info=client_info, + ), + self.update_experiment: gapic_v1.method.wrap_method( + self.update_experiment, + default_timeout=None, + client_info=client_info, + ), + self.delete_experiment: gapic_v1.method.wrap_method( + self.delete_experiment, + default_timeout=None, + client_info=client_info, + ), + self.start_experiment: gapic_v1.method.wrap_method( + self.start_experiment, + default_timeout=None, + client_info=client_info, + ), + self.stop_experiment: gapic_v1.method.wrap_method( + self.stop_experiment, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_experiments(self) -> Callable[ + [experiment.ListExperimentsRequest], + Union[ + experiment.ListExperimentsResponse, + Awaitable[experiment.ListExperimentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_experiment(self) -> Callable[ + [experiment.GetExperimentRequest], + Union[ + experiment.Experiment, + Awaitable[experiment.Experiment] + ]]: + raise NotImplementedError() + + @property + def create_experiment(self) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], + Union[ + gcdc_experiment.Experiment, + Awaitable[gcdc_experiment.Experiment] + ]]: + raise NotImplementedError() + + @property + def update_experiment(self) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], + Union[ + gcdc_experiment.Experiment, + Awaitable[gcdc_experiment.Experiment] + ]]: + raise NotImplementedError() + + @property + def delete_experiment(self) -> Callable[ + [experiment.DeleteExperimentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def start_experiment(self) -> Callable[ + [experiment.StartExperimentRequest], + Union[ + experiment.Experiment, + Awaitable[experiment.Experiment] + ]]: + raise NotImplementedError() + + @property + def stop_experiment(self) -> Callable[ + [experiment.StopExperimentRequest], + Union[ + experiment.Experiment, + Awaitable[experiment.Experiment] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ExperimentsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py new file mode 100644 index 00000000..736fac49 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py @@ -0,0 +1,424 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 # type: ignore +from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO + + +class ExperimentsGrpcTransport(ExperimentsTransport): + """gRPC backend transport for Experiments. + + Service for managing + [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_experiments(self) -> Callable[ + [experiment.ListExperimentsRequest], + experiment.ListExperimentsResponse]: + r"""Return a callable for the list experiments method over gRPC. + + Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.ListExperimentsRequest], + ~.ListExperimentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_experiments' not in self._stubs: + self._stubs['list_experiments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/ListExperiments', + request_serializer=experiment.ListExperimentsRequest.serialize, + response_deserializer=experiment.ListExperimentsResponse.deserialize, + ) + return self._stubs['list_experiments'] + + @property + def get_experiment(self) -> Callable[ + [experiment.GetExperimentRequest], + experiment.Experiment]: + r"""Return a callable for the get experiment method over gRPC. + + Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.GetExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_experiment' not in self._stubs: + self._stubs['get_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/GetExperiment', + request_serializer=experiment.GetExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['get_experiment'] + + @property + def create_experiment(self) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], + gcdc_experiment.Experiment]: + r"""Return a callable for the create experiment method over gRPC. + + Creates an + [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the + specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.CreateExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_experiment' not in self._stubs: + self._stubs['create_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/CreateExperiment', + request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs['create_experiment'] + + @property + def update_experiment(self) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], + gcdc_experiment.Experiment]: + r"""Return a callable for the update experiment method over gRPC. + + Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.UpdateExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_experiment' not in self._stubs: + self._stubs['update_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/UpdateExperiment', + request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs['update_experiment'] + + @property + def delete_experiment(self) -> Callable[ + [experiment.DeleteExperimentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete experiment method over gRPC. + + Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.DeleteExperimentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_experiment' not in self._stubs: + self._stubs['delete_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/DeleteExperiment', + request_serializer=experiment.DeleteExperimentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_experiment'] + + @property + def start_experiment(self) -> Callable[ + [experiment.StartExperimentRequest], + experiment.Experiment]: + r"""Return a callable for the start experiment method over gRPC. + + Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from PENDING to RUNNING. + + Returns: + Callable[[~.StartExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_experiment' not in self._stubs: + self._stubs['start_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/StartExperiment', + request_serializer=experiment.StartExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['start_experiment'] + + @property + def stop_experiment(self) -> Callable[ + [experiment.StopExperimentRequest], + experiment.Experiment]: + r"""Return a callable for the stop experiment method over gRPC. + + Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from RUNNING to DONE. + + Returns: + Callable[[~.StopExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_experiment' not in self._stubs: + self._stubs['stop_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/StopExperiment', + request_serializer=experiment.StopExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['stop_experiment'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'ExperimentsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py new file mode 100644 index 00000000..36ea34af --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py @@ -0,0 +1,429 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 # type: ignore +from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .grpc import ExperimentsGrpcTransport + + +class ExperimentsGrpcAsyncIOTransport(ExperimentsTransport): + """gRPC AsyncIO backend transport for Experiments. + + Service for managing + [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_experiments(self) -> Callable[ + [experiment.ListExperimentsRequest], + Awaitable[experiment.ListExperimentsResponse]]: + r"""Return a callable for the list experiments method over gRPC. + + Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.ListExperimentsRequest], + Awaitable[~.ListExperimentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_experiments' not in self._stubs: + self._stubs['list_experiments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/ListExperiments', + request_serializer=experiment.ListExperimentsRequest.serialize, + response_deserializer=experiment.ListExperimentsResponse.deserialize, + ) + return self._stubs['list_experiments'] + + @property + def get_experiment(self) -> Callable[ + [experiment.GetExperimentRequest], + Awaitable[experiment.Experiment]]: + r"""Return a callable for the get experiment method over gRPC. + + Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.GetExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_experiment' not in self._stubs: + self._stubs['get_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/GetExperiment', + request_serializer=experiment.GetExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['get_experiment'] + + @property + def create_experiment(self) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], + Awaitable[gcdc_experiment.Experiment]]: + r"""Return a callable for the create experiment method over gRPC. + + Creates an + [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the + specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.CreateExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_experiment' not in self._stubs: + self._stubs['create_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/CreateExperiment', + request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs['create_experiment'] + + @property + def update_experiment(self) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], + Awaitable[gcdc_experiment.Experiment]]: + r"""Return a callable for the update experiment method over gRPC. + + Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.UpdateExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_experiment' not in self._stubs: + self._stubs['update_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/UpdateExperiment', + request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs['update_experiment'] + + @property + def delete_experiment(self) -> Callable[ + [experiment.DeleteExperimentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete experiment method over gRPC. + + Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.DeleteExperimentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_experiment' not in self._stubs: + self._stubs['delete_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/DeleteExperiment', + request_serializer=experiment.DeleteExperimentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_experiment'] + + @property + def start_experiment(self) -> Callable[ + [experiment.StartExperimentRequest], + Awaitable[experiment.Experiment]]: + r"""Return a callable for the start experiment method over gRPC. + + Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from PENDING to RUNNING. + + Returns: + Callable[[~.StartExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_experiment' not in self._stubs: + self._stubs['start_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/StartExperiment', + request_serializer=experiment.StartExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['start_experiment'] + + @property + def stop_experiment(self) -> Callable[ + [experiment.StopExperimentRequest], + Awaitable[experiment.Experiment]]: + r"""Return a callable for the stop experiment method over gRPC. + + Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from RUNNING to DONE. + + Returns: + Callable[[~.StopExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_experiment' not in self._stubs: + self._stubs['stop_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/StopExperiment', + request_serializer=experiment.StopExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['stop_experiment'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'ExperimentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/__init__.py new file mode 100644 index 00000000..42e3f705 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import FlowsClient +from .async_client import FlowsAsyncClient + +__all__ = ( + 'FlowsClient', + 'FlowsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/async_client.py new file mode 100644 index 00000000..01109cd5 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/async_client.py @@ -0,0 +1,1057 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflowcx_v3.services.flows import pagers +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import validation_message +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport +from .client import FlowsClient + + +class FlowsAsyncClient: + """Service for managing [Flows][google.cloud.dialogflow.cx.v3.Flow].""" + + _client: FlowsClient + + DEFAULT_ENDPOINT = FlowsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FlowsClient.DEFAULT_MTLS_ENDPOINT + + flow_path = staticmethod(FlowsClient.flow_path) + parse_flow_path = staticmethod(FlowsClient.parse_flow_path) + flow_validation_result_path = staticmethod(FlowsClient.flow_validation_result_path) + parse_flow_validation_result_path = staticmethod(FlowsClient.parse_flow_validation_result_path) + intent_path = staticmethod(FlowsClient.intent_path) + parse_intent_path = staticmethod(FlowsClient.parse_intent_path) + page_path = staticmethod(FlowsClient.page_path) + parse_page_path = staticmethod(FlowsClient.parse_page_path) + transition_route_group_path = staticmethod(FlowsClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(FlowsClient.parse_transition_route_group_path) + webhook_path = staticmethod(FlowsClient.webhook_path) + parse_webhook_path = staticmethod(FlowsClient.parse_webhook_path) + common_billing_account_path = staticmethod(FlowsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(FlowsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(FlowsClient.common_folder_path) + parse_common_folder_path = staticmethod(FlowsClient.parse_common_folder_path) + common_organization_path = staticmethod(FlowsClient.common_organization_path) + parse_common_organization_path = staticmethod(FlowsClient.parse_common_organization_path) + common_project_path = staticmethod(FlowsClient.common_project_path) + parse_common_project_path = staticmethod(FlowsClient.parse_common_project_path) + common_location_path = staticmethod(FlowsClient.common_location_path) + parse_common_location_path = staticmethod(FlowsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FlowsAsyncClient: The constructed client. + """ + return FlowsClient.from_service_account_info.__func__(FlowsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FlowsAsyncClient: The constructed client. + """ + return FlowsClient.from_service_account_file.__func__(FlowsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FlowsTransport: + """Returns the transport used by the client instance. + + Returns: + FlowsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(FlowsClient).get_transport_class, type(FlowsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FlowsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the flows client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.FlowsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = FlowsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_flow(self, + request: gcdc_flow.CreateFlowRequest = None, + *, + parent: str = None, + flow: gcdc_flow.Flow = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_flow.Flow: + r"""Creates a flow in the specified agent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateFlowRequest`): + The request object. The request message for + [Flows.CreateFlow][google.cloud.dialogflow.cx.v3.Flows.CreateFlow]. + parent (:class:`str`): + Required. The agent to create a flow for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + flow (:class:`google.cloud.dialogflowcx_v3.types.Flow`): + Required. The flow to create. + This corresponds to the ``flow`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, flow]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_flow.CreateFlowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if flow is not None: + request.flow = flow + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_flow(self, + request: flow.DeleteFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteFlowRequest`): + The request object. The request message for + [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3.Flows.DeleteFlow]. + name (:class:`str`): + Required. The name of the flow to delete. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = flow.DeleteFlowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_flows(self, + request: flow.ListFlowsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFlowsAsyncPager: + r"""Returns the list of all flows in the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListFlowsRequest`): + The request object. The request message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. + parent (:class:`str`): + Required. The agent containing the flows. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.flows.pagers.ListFlowsAsyncPager: + The response message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = flow.ListFlowsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_flows, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListFlowsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_flow(self, + request: flow.GetFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.Flow: + r"""Retrieves the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetFlowRequest`): + The request object. The response message for + [Flows.GetFlow][google.cloud.dialogflow.cx.v3.Flows.GetFlow]. + name (:class:`str`): + Required. The name of the flow to get. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = flow.GetFlowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_flow(self, + request: gcdc_flow.UpdateFlowRequest = None, + *, + flow: gcdc_flow.Flow = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_flow.Flow: + r"""Updates the specified flow. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateFlowRequest`): + The request object. The request message for + [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3.Flows.UpdateFlow]. + flow (:class:`google.cloud.dialogflowcx_v3.types.Flow`): + Required. The flow to update. + This corresponds to the ``flow`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The mask to control which fields get + updated. If the mask is not present, all + fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([flow, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_flow.UpdateFlowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if flow is not None: + request.flow = flow + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("flow.name", request.flow.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def train_flow(self, + request: flow.TrainFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Trains the specified flow. Note that only the flow in 'draft' + environment is trained. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.TrainFlowRequest`): + The request object. The request message for + [Flows.TrainFlow][google.cloud.dialogflow.cx.v3.Flows.TrainFlow]. + name (:class:`str`): + Required. The flow to train. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = flow.TrainFlowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.train_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def validate_flow(self, + request: flow.ValidateFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.FlowValidationResult: + r"""Validates the specified flow and creates or updates + validation results. Please call this API after the + training is completed to get the complete validation + results. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ValidateFlowRequest`): + The request object. The request message for + [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3.Flows.ValidateFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.FlowValidationResult: + The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + + """ + # Create or coerce a protobuf request object. + request = flow.ValidateFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.validate_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_flow_validation_result(self, + request: flow.GetFlowValidationResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.FlowValidationResult: + r"""Gets the latest flow validation result. Flow + validation is performed when ValidateFlow is called. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetFlowValidationResultRequest`): + The request object. The request message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + name (:class:`str`): + Required. The flow name. Format: + ``projects//locations//agents//flows//validationResult``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.FlowValidationResult: + The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = flow.GetFlowValidationResultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_flow_validation_result, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_flow(self, + request: flow.ImportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports the specified flow to the specified agent from a binary + file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ImportFlowResponse][google.cloud.dialogflow.cx.v3.ImportFlowResponse] + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ImportFlowRequest`): + The request object. The request message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ImportFlowResponse` + The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + + """ + # Create or coerce a protobuf request object. + request = flow.ImportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + flow.ImportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def export_flow(self, + request: flow.ExportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the specified flow to a binary file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportFlowResponse][google.cloud.dialogflow.cx.v3.ExportFlowResponse] + + Note that resources (e.g. intents, entities, webhooks) that the + flow references will also be exported. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ExportFlowRequest`): + The request object. The request message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportFlowResponse` + The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + + """ + # Create or coerce a protobuf request object. + request = flow.ExportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + flow.ExportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FlowsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/client.py new file mode 100644 index 00000000..56cd4aa3 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/client.py @@ -0,0 +1,1302 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflowcx_v3.services.flows import pagers +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import validation_message +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FlowsGrpcTransport +from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport + + +class FlowsClientMeta(type): + """Metaclass for the Flows client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[FlowsTransport]] + _transport_registry["grpc"] = FlowsGrpcTransport + _transport_registry["grpc_asyncio"] = FlowsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[FlowsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class FlowsClient(metaclass=FlowsClientMeta): + """Service for managing [Flows][google.cloud.dialogflow.cx.v3.Flow].""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FlowsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FlowsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FlowsTransport: + """Returns the transport used by the client instance. + + Returns: + FlowsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_validation_result_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow_validation_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_validation_result_path(path: str) -> Dict[str,str]: + """Parses a flow_validation_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FlowsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the flows client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, FlowsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, FlowsTransport): + # transport is a FlowsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_flow(self, + request: Union[gcdc_flow.CreateFlowRequest, dict] = None, + *, + parent: str = None, + flow: gcdc_flow.Flow = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_flow.Flow: + r"""Creates a flow in the specified agent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateFlowRequest, dict]): + The request object. The request message for + [Flows.CreateFlow][google.cloud.dialogflow.cx.v3.Flows.CreateFlow]. + parent (str): + Required. The agent to create a flow for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + flow (google.cloud.dialogflowcx_v3.types.Flow): + Required. The flow to create. + This corresponds to the ``flow`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, flow]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_flow.CreateFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_flow.CreateFlowRequest): + request = gcdc_flow.CreateFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if flow is not None: + request.flow = flow + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_flow(self, + request: Union[flow.DeleteFlowRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a specified flow. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteFlowRequest, dict]): + The request object. The request message for + [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3.Flows.DeleteFlow]. + name (str): + Required. The name of the flow to delete. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a flow.DeleteFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.DeleteFlowRequest): + request = flow.DeleteFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_flows(self, + request: Union[flow.ListFlowsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFlowsPager: + r"""Returns the list of all flows in the specified agent. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListFlowsRequest, dict]): + The request object. The request message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. + parent (str): + Required. The agent containing the flows. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.flows.pagers.ListFlowsPager: + The response message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a flow.ListFlowsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ListFlowsRequest): + request = flow.ListFlowsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_flows] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListFlowsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_flow(self, + request: Union[flow.GetFlowRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.Flow: + r"""Retrieves the specified flow. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetFlowRequest, dict]): + The request object. The response message for + [Flows.GetFlow][google.cloud.dialogflow.cx.v3.Flows.GetFlow]. + name (str): + Required. The name of the flow to get. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a flow.GetFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.GetFlowRequest): + request = flow.GetFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_flow(self, + request: Union[gcdc_flow.UpdateFlowRequest, dict] = None, + *, + flow: gcdc_flow.Flow = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_flow.Flow: + r"""Updates the specified flow. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateFlowRequest, dict]): + The request object. The request message for + [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3.Flows.UpdateFlow]. + flow (google.cloud.dialogflowcx_v3.types.Flow): + Required. The flow to update. + This corresponds to the ``flow`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get + updated. If the mask is not present, all + fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([flow, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_flow.UpdateFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_flow.UpdateFlowRequest): + request = gcdc_flow.UpdateFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if flow is not None: + request.flow = flow + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("flow.name", request.flow.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def train_flow(self, + request: Union[flow.TrainFlowRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Trains the specified flow. Note that only the flow in 'draft' + environment is trained. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.TrainFlowRequest, dict]): + The request object. The request message for + [Flows.TrainFlow][google.cloud.dialogflow.cx.v3.Flows.TrainFlow]. + name (str): + Required. The flow to train. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a flow.TrainFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.TrainFlowRequest): + request = flow.TrainFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.train_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def validate_flow(self, + request: Union[flow.ValidateFlowRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.FlowValidationResult: + r"""Validates the specified flow and creates or updates + validation results. Please call this API after the + training is completed to get the complete validation + results. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ValidateFlowRequest, dict]): + The request object. The request message for + [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3.Flows.ValidateFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.FlowValidationResult: + The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ValidateFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ValidateFlowRequest): + request = flow.ValidateFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_flow_validation_result(self, + request: Union[flow.GetFlowValidationResultRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.FlowValidationResult: + r"""Gets the latest flow validation result. Flow + validation is performed when ValidateFlow is called. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetFlowValidationResultRequest, dict]): + The request object. The request message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + name (str): + Required. The flow name. Format: + ``projects//locations//agents//flows//validationResult``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.FlowValidationResult: + The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a flow.GetFlowValidationResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.GetFlowValidationResultRequest): + request = flow.GetFlowValidationResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_flow_validation_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_flow(self, + request: Union[flow.ImportFlowRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports the specified flow to the specified agent from a binary + file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ImportFlowResponse][google.cloud.dialogflow.cx.v3.ImportFlowResponse] + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ImportFlowRequest, dict]): + The request object. The request message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ImportFlowResponse` + The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ImportFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ImportFlowRequest): + request = flow.ImportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + flow.ImportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def export_flow(self, + request: Union[flow.ExportFlowRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the specified flow to a binary file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportFlowResponse][google.cloud.dialogflow.cx.v3.ExportFlowResponse] + + Note that resources (e.g. intents, entities, webhooks) that the + flow references will also be exported. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ExportFlowRequest, dict]): + The request object. The request message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportFlowResponse` + The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ExportFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ExportFlowRequest): + request = flow.ExportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + flow.ExportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FlowsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/pagers.py new file mode 100644 index 00000000..87e4b33e --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import flow + + +class ListFlowsPager: + """A pager for iterating through ``list_flows`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListFlowsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``flows`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFlows`` requests and continue to iterate + through the ``flows`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListFlowsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., flow.ListFlowsResponse], + request: flow.ListFlowsRequest, + response: flow.ListFlowsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListFlowsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListFlowsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = flow.ListFlowsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[flow.ListFlowsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[flow.Flow]: + for page in self.pages: + yield from page.flows + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFlowsAsyncPager: + """A pager for iterating through ``list_flows`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListFlowsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``flows`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFlows`` requests and continue to iterate + through the ``flows`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListFlowsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[flow.ListFlowsResponse]], + request: flow.ListFlowsRequest, + response: flow.ListFlowsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListFlowsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListFlowsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = flow.ListFlowsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[flow.ListFlowsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[flow.Flow]: + async def async_generator(): + async for page in self.pages: + for response in page.flows: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py new file mode 100644 index 00000000..4ba28aff --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import FlowsTransport +from .grpc import FlowsGrpcTransport +from .grpc_asyncio import FlowsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FlowsTransport]] +_transport_registry['grpc'] = FlowsGrpcTransport +_transport_registry['grpc_asyncio'] = FlowsGrpcAsyncIOTransport + +__all__ = ( + 'FlowsTransport', + 'FlowsGrpcTransport', + 'FlowsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/base.py new file mode 100644 index 00000000..cb451fea --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/base.py @@ -0,0 +1,313 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class FlowsTransport(abc.ABC): + """Abstract transport class for Flows.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_flow: gapic_v1.method.wrap_method( + self.create_flow, + default_timeout=None, + client_info=client_info, + ), + self.delete_flow: gapic_v1.method.wrap_method( + self.delete_flow, + default_timeout=None, + client_info=client_info, + ), + self.list_flows: gapic_v1.method.wrap_method( + self.list_flows, + default_timeout=None, + client_info=client_info, + ), + self.get_flow: gapic_v1.method.wrap_method( + self.get_flow, + default_timeout=None, + client_info=client_info, + ), + self.update_flow: gapic_v1.method.wrap_method( + self.update_flow, + default_timeout=None, + client_info=client_info, + ), + self.train_flow: gapic_v1.method.wrap_method( + self.train_flow, + default_timeout=None, + client_info=client_info, + ), + self.validate_flow: gapic_v1.method.wrap_method( + self.validate_flow, + default_timeout=None, + client_info=client_info, + ), + self.get_flow_validation_result: gapic_v1.method.wrap_method( + self.get_flow_validation_result, + default_timeout=None, + client_info=client_info, + ), + self.import_flow: gapic_v1.method.wrap_method( + self.import_flow, + default_timeout=None, + client_info=client_info, + ), + self.export_flow: gapic_v1.method.wrap_method( + self.export_flow, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_flow(self) -> Callable[ + [gcdc_flow.CreateFlowRequest], + Union[ + gcdc_flow.Flow, + Awaitable[gcdc_flow.Flow] + ]]: + raise NotImplementedError() + + @property + def delete_flow(self) -> Callable[ + [flow.DeleteFlowRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_flows(self) -> Callable[ + [flow.ListFlowsRequest], + Union[ + flow.ListFlowsResponse, + Awaitable[flow.ListFlowsResponse] + ]]: + raise NotImplementedError() + + @property + def get_flow(self) -> Callable[ + [flow.GetFlowRequest], + Union[ + flow.Flow, + Awaitable[flow.Flow] + ]]: + raise NotImplementedError() + + @property + def update_flow(self) -> Callable[ + [gcdc_flow.UpdateFlowRequest], + Union[ + gcdc_flow.Flow, + Awaitable[gcdc_flow.Flow] + ]]: + raise NotImplementedError() + + @property + def train_flow(self) -> Callable[ + [flow.TrainFlowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def validate_flow(self) -> Callable[ + [flow.ValidateFlowRequest], + Union[ + flow.FlowValidationResult, + Awaitable[flow.FlowValidationResult] + ]]: + raise NotImplementedError() + + @property + def get_flow_validation_result(self) -> Callable[ + [flow.GetFlowValidationResultRequest], + Union[ + flow.FlowValidationResult, + Awaitable[flow.FlowValidationResult] + ]]: + raise NotImplementedError() + + @property + def import_flow(self) -> Callable[ + [flow.ImportFlowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_flow(self) -> Callable[ + [flow.ExportFlowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'FlowsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py new file mode 100644 index 00000000..599f9476 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py @@ -0,0 +1,564 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import FlowsTransport, DEFAULT_CLIENT_INFO + + +class FlowsGrpcTransport(FlowsTransport): + """gRPC backend transport for Flows. + + Service for managing [Flows][google.cloud.dialogflow.cx.v3.Flow]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_flow(self) -> Callable[ + [gcdc_flow.CreateFlowRequest], + gcdc_flow.Flow]: + r"""Return a callable for the create flow method over gRPC. + + Creates a flow in the specified agent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateFlowRequest], + ~.Flow]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_flow' not in self._stubs: + self._stubs['create_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/CreateFlow', + request_serializer=gcdc_flow.CreateFlowRequest.serialize, + response_deserializer=gcdc_flow.Flow.deserialize, + ) + return self._stubs['create_flow'] + + @property + def delete_flow(self) -> Callable[ + [flow.DeleteFlowRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete flow method over gRPC. + + Deletes a specified flow. + + Returns: + Callable[[~.DeleteFlowRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_flow' not in self._stubs: + self._stubs['delete_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/DeleteFlow', + request_serializer=flow.DeleteFlowRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_flow'] + + @property + def list_flows(self) -> Callable[ + [flow.ListFlowsRequest], + flow.ListFlowsResponse]: + r"""Return a callable for the list flows method over gRPC. + + Returns the list of all flows in the specified agent. + + Returns: + Callable[[~.ListFlowsRequest], + ~.ListFlowsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_flows' not in self._stubs: + self._stubs['list_flows'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ListFlows', + request_serializer=flow.ListFlowsRequest.serialize, + response_deserializer=flow.ListFlowsResponse.deserialize, + ) + return self._stubs['list_flows'] + + @property + def get_flow(self) -> Callable[ + [flow.GetFlowRequest], + flow.Flow]: + r"""Return a callable for the get flow method over gRPC. + + Retrieves the specified flow. + + Returns: + Callable[[~.GetFlowRequest], + ~.Flow]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_flow' not in self._stubs: + self._stubs['get_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/GetFlow', + request_serializer=flow.GetFlowRequest.serialize, + response_deserializer=flow.Flow.deserialize, + ) + return self._stubs['get_flow'] + + @property + def update_flow(self) -> Callable[ + [gcdc_flow.UpdateFlowRequest], + gcdc_flow.Flow]: + r"""Return a callable for the update flow method over gRPC. + + Updates the specified flow. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateFlowRequest], + ~.Flow]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_flow' not in self._stubs: + self._stubs['update_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/UpdateFlow', + request_serializer=gcdc_flow.UpdateFlowRequest.serialize, + response_deserializer=gcdc_flow.Flow.deserialize, + ) + return self._stubs['update_flow'] + + @property + def train_flow(self) -> Callable[ + [flow.TrainFlowRequest], + operations_pb2.Operation]: + r"""Return a callable for the train flow method over gRPC. + + Trains the specified flow. Note that only the flow in 'draft' + environment is trained. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.TrainFlowRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'train_flow' not in self._stubs: + self._stubs['train_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/TrainFlow', + request_serializer=flow.TrainFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['train_flow'] + + @property + def validate_flow(self) -> Callable[ + [flow.ValidateFlowRequest], + flow.FlowValidationResult]: + r"""Return a callable for the validate flow method over gRPC. + + Validates the specified flow and creates or updates + validation results. Please call this API after the + training is completed to get the complete validation + results. + + Returns: + Callable[[~.ValidateFlowRequest], + ~.FlowValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_flow' not in self._stubs: + self._stubs['validate_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ValidateFlow', + request_serializer=flow.ValidateFlowRequest.serialize, + response_deserializer=flow.FlowValidationResult.deserialize, + ) + return self._stubs['validate_flow'] + + @property + def get_flow_validation_result(self) -> Callable[ + [flow.GetFlowValidationResultRequest], + flow.FlowValidationResult]: + r"""Return a callable for the get flow validation result method over gRPC. + + Gets the latest flow validation result. Flow + validation is performed when ValidateFlow is called. + + Returns: + Callable[[~.GetFlowValidationResultRequest], + ~.FlowValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_flow_validation_result' not in self._stubs: + self._stubs['get_flow_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/GetFlowValidationResult', + request_serializer=flow.GetFlowValidationResultRequest.serialize, + response_deserializer=flow.FlowValidationResult.deserialize, + ) + return self._stubs['get_flow_validation_result'] + + @property + def import_flow(self) -> Callable[ + [flow.ImportFlowRequest], + operations_pb2.Operation]: + r"""Return a callable for the import flow method over gRPC. + + Imports the specified flow to the specified agent from a binary + file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ImportFlowResponse][google.cloud.dialogflow.cx.v3.ImportFlowResponse] + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.ImportFlowRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_flow' not in self._stubs: + self._stubs['import_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ImportFlow', + request_serializer=flow.ImportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_flow'] + + @property + def export_flow(self) -> Callable[ + [flow.ExportFlowRequest], + operations_pb2.Operation]: + r"""Return a callable for the export flow method over gRPC. + + Exports the specified flow to a binary file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportFlowResponse][google.cloud.dialogflow.cx.v3.ExportFlowResponse] + + Note that resources (e.g. intents, entities, webhooks) that the + flow references will also be exported. + + Returns: + Callable[[~.ExportFlowRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_flow' not in self._stubs: + self._stubs['export_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ExportFlow', + request_serializer=flow.ExportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_flow'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'FlowsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py new file mode 100644 index 00000000..12979879 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py @@ -0,0 +1,569 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import FlowsTransport, DEFAULT_CLIENT_INFO +from .grpc import FlowsGrpcTransport + + +class FlowsGrpcAsyncIOTransport(FlowsTransport): + """gRPC AsyncIO backend transport for Flows. + + Service for managing [Flows][google.cloud.dialogflow.cx.v3.Flow]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_flow(self) -> Callable[ + [gcdc_flow.CreateFlowRequest], + Awaitable[gcdc_flow.Flow]]: + r"""Return a callable for the create flow method over gRPC. + + Creates a flow in the specified agent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateFlowRequest], + Awaitable[~.Flow]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_flow' not in self._stubs: + self._stubs['create_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/CreateFlow', + request_serializer=gcdc_flow.CreateFlowRequest.serialize, + response_deserializer=gcdc_flow.Flow.deserialize, + ) + return self._stubs['create_flow'] + + @property + def delete_flow(self) -> Callable[ + [flow.DeleteFlowRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete flow method over gRPC. + + Deletes a specified flow. + + Returns: + Callable[[~.DeleteFlowRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_flow' not in self._stubs: + self._stubs['delete_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/DeleteFlow', + request_serializer=flow.DeleteFlowRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_flow'] + + @property + def list_flows(self) -> Callable[ + [flow.ListFlowsRequest], + Awaitable[flow.ListFlowsResponse]]: + r"""Return a callable for the list flows method over gRPC. + + Returns the list of all flows in the specified agent. + + Returns: + Callable[[~.ListFlowsRequest], + Awaitable[~.ListFlowsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_flows' not in self._stubs: + self._stubs['list_flows'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ListFlows', + request_serializer=flow.ListFlowsRequest.serialize, + response_deserializer=flow.ListFlowsResponse.deserialize, + ) + return self._stubs['list_flows'] + + @property + def get_flow(self) -> Callable[ + [flow.GetFlowRequest], + Awaitable[flow.Flow]]: + r"""Return a callable for the get flow method over gRPC. + + Retrieves the specified flow. + + Returns: + Callable[[~.GetFlowRequest], + Awaitable[~.Flow]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_flow' not in self._stubs: + self._stubs['get_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/GetFlow', + request_serializer=flow.GetFlowRequest.serialize, + response_deserializer=flow.Flow.deserialize, + ) + return self._stubs['get_flow'] + + @property + def update_flow(self) -> Callable[ + [gcdc_flow.UpdateFlowRequest], + Awaitable[gcdc_flow.Flow]]: + r"""Return a callable for the update flow method over gRPC. + + Updates the specified flow. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateFlowRequest], + Awaitable[~.Flow]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_flow' not in self._stubs: + self._stubs['update_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/UpdateFlow', + request_serializer=gcdc_flow.UpdateFlowRequest.serialize, + response_deserializer=gcdc_flow.Flow.deserialize, + ) + return self._stubs['update_flow'] + + @property + def train_flow(self) -> Callable[ + [flow.TrainFlowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the train flow method over gRPC. + + Trains the specified flow. Note that only the flow in 'draft' + environment is trained. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.TrainFlowRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'train_flow' not in self._stubs: + self._stubs['train_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/TrainFlow', + request_serializer=flow.TrainFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['train_flow'] + + @property + def validate_flow(self) -> Callable[ + [flow.ValidateFlowRequest], + Awaitable[flow.FlowValidationResult]]: + r"""Return a callable for the validate flow method over gRPC. + + Validates the specified flow and creates or updates + validation results. Please call this API after the + training is completed to get the complete validation + results. + + Returns: + Callable[[~.ValidateFlowRequest], + Awaitable[~.FlowValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_flow' not in self._stubs: + self._stubs['validate_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ValidateFlow', + request_serializer=flow.ValidateFlowRequest.serialize, + response_deserializer=flow.FlowValidationResult.deserialize, + ) + return self._stubs['validate_flow'] + + @property + def get_flow_validation_result(self) -> Callable[ + [flow.GetFlowValidationResultRequest], + Awaitable[flow.FlowValidationResult]]: + r"""Return a callable for the get flow validation result method over gRPC. + + Gets the latest flow validation result. Flow + validation is performed when ValidateFlow is called. + + Returns: + Callable[[~.GetFlowValidationResultRequest], + Awaitable[~.FlowValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_flow_validation_result' not in self._stubs: + self._stubs['get_flow_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/GetFlowValidationResult', + request_serializer=flow.GetFlowValidationResultRequest.serialize, + response_deserializer=flow.FlowValidationResult.deserialize, + ) + return self._stubs['get_flow_validation_result'] + + @property + def import_flow(self) -> Callable[ + [flow.ImportFlowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import flow method over gRPC. + + Imports the specified flow to the specified agent from a binary + file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ImportFlowResponse][google.cloud.dialogflow.cx.v3.ImportFlowResponse] + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.ImportFlowRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_flow' not in self._stubs: + self._stubs['import_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ImportFlow', + request_serializer=flow.ImportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_flow'] + + @property + def export_flow(self) -> Callable[ + [flow.ExportFlowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export flow method over gRPC. + + Exports the specified flow to a binary file. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: + [ExportFlowResponse][google.cloud.dialogflow.cx.v3.ExportFlowResponse] + + Note that resources (e.g. intents, entities, webhooks) that the + flow references will also be exported. + + Returns: + Callable[[~.ExportFlowRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_flow' not in self._stubs: + self._stubs['export_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ExportFlow', + request_serializer=flow.ExportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_flow'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'FlowsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/__init__.py new file mode 100644 index 00000000..8204500f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import IntentsClient +from .async_client import IntentsAsyncClient + +__all__ = ( + 'IntentsClient', + 'IntentsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/async_client.py new file mode 100644 index 00000000..1bac4e8d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/async_client.py @@ -0,0 +1,594 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.intents import pagers +from google.cloud.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport +from .client import IntentsClient + + +class IntentsAsyncClient: + """Service for managing + [Intents][google.cloud.dialogflow.cx.v3.Intent]. + """ + + _client: IntentsClient + + DEFAULT_ENDPOINT = IntentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = IntentsClient.DEFAULT_MTLS_ENDPOINT + + entity_type_path = staticmethod(IntentsClient.entity_type_path) + parse_entity_type_path = staticmethod(IntentsClient.parse_entity_type_path) + intent_path = staticmethod(IntentsClient.intent_path) + parse_intent_path = staticmethod(IntentsClient.parse_intent_path) + common_billing_account_path = staticmethod(IntentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(IntentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(IntentsClient.common_folder_path) + parse_common_folder_path = staticmethod(IntentsClient.parse_common_folder_path) + common_organization_path = staticmethod(IntentsClient.common_organization_path) + parse_common_organization_path = staticmethod(IntentsClient.parse_common_organization_path) + common_project_path = staticmethod(IntentsClient.common_project_path) + parse_common_project_path = staticmethod(IntentsClient.parse_common_project_path) + common_location_path = staticmethod(IntentsClient.common_location_path) + parse_common_location_path = staticmethod(IntentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IntentsAsyncClient: The constructed client. + """ + return IntentsClient.from_service_account_info.__func__(IntentsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IntentsAsyncClient: The constructed client. + """ + return IntentsClient.from_service_account_file.__func__(IntentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> IntentsTransport: + """Returns the transport used by the client instance. + + Returns: + IntentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(IntentsClient).get_transport_class, type(IntentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, IntentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the intents client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.IntentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = IntentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_intents(self, + request: intent.ListIntentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIntentsAsyncPager: + r"""Returns the list of all intents in the specified + agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListIntentsRequest`): + The request object. The request message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. + parent (:class:`str`): + Required. The agent to list all intents for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.intents.pagers.ListIntentsAsyncPager: + The response message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = intent.ListIntentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_intents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListIntentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_intent(self, + request: intent.GetIntentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> intent.Intent: + r"""Retrieves the specified intent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetIntentRequest`): + The request object. The request message for + [Intents.GetIntent][google.cloud.dialogflow.cx.v3.Intents.GetIntent]. + name (:class:`str`): + Required. The name of the intent. Format: + ``projects//locations//agents//intents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = intent.GetIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_intent(self, + request: gcdc_intent.CreateIntentRequest = None, + *, + parent: str = None, + intent: gcdc_intent.Intent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_intent.Intent: + r"""Creates an intent in the specified agent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateIntentRequest`): + The request object. The request message for + [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent]. + parent (:class:`str`): + Required. The agent to create an intent for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent (:class:`google.cloud.dialogflowcx_v3.types.Intent`): + Required. The intent to create. + This corresponds to the ``intent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, intent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_intent.CreateIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent is not None: + request.intent = intent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_intent(self, + request: gcdc_intent.UpdateIntentRequest = None, + *, + intent: gcdc_intent.Intent = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_intent.Intent: + r"""Updates the specified intent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateIntentRequest`): + The request object. The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent]. + intent (:class:`google.cloud.dialogflowcx_v3.types.Intent`): + Required. The intent to update. + This corresponds to the ``intent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The mask to control which fields get + updated. If the mask is not present, all + fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([intent, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_intent.UpdateIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intent is not None: + request.intent = intent + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("intent.name", request.intent.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_intent(self, + request: intent.DeleteIntentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified intent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteIntentRequest`): + The request object. The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3.Intents.DeleteIntent]. + name (:class:`str`): + Required. The name of the intent to delete. Format: + ``projects//locations//agents//intents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = intent.DeleteIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "IntentsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/client.py new file mode 100644 index 00000000..386bf5fe --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/client.py @@ -0,0 +1,800 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.intents import pagers +from google.cloud.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import IntentsGrpcTransport +from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport + + +class IntentsClientMeta(type): + """Metaclass for the Intents client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[IntentsTransport]] + _transport_registry["grpc"] = IntentsGrpcTransport + _transport_registry["grpc_asyncio"] = IntentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[IntentsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class IntentsClient(metaclass=IntentsClientMeta): + """Service for managing + [Intents][google.cloud.dialogflow.cx.v3.Intent]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IntentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IntentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> IntentsTransport: + """Returns the transport used by the client instance. + + Returns: + IntentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, IntentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the intents client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, IntentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, IntentsTransport): + # transport is a IntentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_intents(self, + request: Union[intent.ListIntentsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIntentsPager: + r"""Returns the list of all intents in the specified + agent. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListIntentsRequest, dict]): + The request object. The request message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. + parent (str): + Required. The agent to list all intents for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.intents.pagers.ListIntentsPager: + The response message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a intent.ListIntentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.ListIntentsRequest): + request = intent.ListIntentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_intents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListIntentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_intent(self, + request: Union[intent.GetIntentRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> intent.Intent: + r"""Retrieves the specified intent. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetIntentRequest, dict]): + The request object. The request message for + [Intents.GetIntent][google.cloud.dialogflow.cx.v3.Intents.GetIntent]. + name (str): + Required. The name of the intent. Format: + ``projects//locations//agents//intents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a intent.GetIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.GetIntentRequest): + request = intent.GetIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_intent(self, + request: Union[gcdc_intent.CreateIntentRequest, dict] = None, + *, + parent: str = None, + intent: gcdc_intent.Intent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_intent.Intent: + r"""Creates an intent in the specified agent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateIntentRequest, dict]): + The request object. The request message for + [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent]. + parent (str): + Required. The agent to create an intent for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent (google.cloud.dialogflowcx_v3.types.Intent): + Required. The intent to create. + This corresponds to the ``intent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, intent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_intent.CreateIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_intent.CreateIntentRequest): + request = gcdc_intent.CreateIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent is not None: + request.intent = intent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_intent(self, + request: Union[gcdc_intent.UpdateIntentRequest, dict] = None, + *, + intent: gcdc_intent.Intent = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_intent.Intent: + r"""Updates the specified intent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateIntentRequest, dict]): + The request object. The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent]. + intent (google.cloud.dialogflowcx_v3.types.Intent): + Required. The intent to update. + This corresponds to the ``intent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get + updated. If the mask is not present, all + fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([intent, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_intent.UpdateIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_intent.UpdateIntentRequest): + request = gcdc_intent.UpdateIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intent is not None: + request.intent = intent + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("intent.name", request.intent.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_intent(self, + request: Union[intent.DeleteIntentRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified intent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteIntentRequest, dict]): + The request object. The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3.Intents.DeleteIntent]. + name (str): + Required. The name of the intent to delete. Format: + ``projects//locations//agents//intents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a intent.DeleteIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, intent.DeleteIntentRequest): + request = intent.DeleteIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "IntentsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/pagers.py new file mode 100644 index 00000000..93903df2 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import intent + + +class ListIntentsPager: + """A pager for iterating through ``list_intents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListIntentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``intents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListIntents`` requests and continue to iterate + through the ``intents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListIntentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., intent.ListIntentsResponse], + request: intent.ListIntentsRequest, + response: intent.ListIntentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListIntentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListIntentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = intent.ListIntentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[intent.ListIntentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[intent.Intent]: + for page in self.pages: + yield from page.intents + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListIntentsAsyncPager: + """A pager for iterating through ``list_intents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListIntentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``intents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListIntents`` requests and continue to iterate + through the ``intents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListIntentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[intent.ListIntentsResponse]], + request: intent.ListIntentsRequest, + response: intent.ListIntentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListIntentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListIntentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = intent.ListIntentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[intent.ListIntentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[intent.Intent]: + async def async_generator(): + async for page in self.pages: + for response in page.intents: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py new file mode 100644 index 00000000..aa8039bb --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import IntentsTransport +from .grpc import IntentsGrpcTransport +from .grpc_asyncio import IntentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[IntentsTransport]] +_transport_registry['grpc'] = IntentsGrpcTransport +_transport_registry['grpc_asyncio'] = IntentsGrpcAsyncIOTransport + +__all__ = ( + 'IntentsTransport', + 'IntentsGrpcTransport', + 'IntentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/base.py new file mode 100644 index 00000000..8f5913e6 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/base.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class IntentsTransport(abc.ABC): + """Abstract transport class for Intents.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_intents: gapic_v1.method.wrap_method( + self.list_intents, + default_timeout=None, + client_info=client_info, + ), + self.get_intent: gapic_v1.method.wrap_method( + self.get_intent, + default_timeout=None, + client_info=client_info, + ), + self.create_intent: gapic_v1.method.wrap_method( + self.create_intent, + default_timeout=None, + client_info=client_info, + ), + self.update_intent: gapic_v1.method.wrap_method( + self.update_intent, + default_timeout=None, + client_info=client_info, + ), + self.delete_intent: gapic_v1.method.wrap_method( + self.delete_intent, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_intents(self) -> Callable[ + [intent.ListIntentsRequest], + Union[ + intent.ListIntentsResponse, + Awaitable[intent.ListIntentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_intent(self) -> Callable[ + [intent.GetIntentRequest], + Union[ + intent.Intent, + Awaitable[intent.Intent] + ]]: + raise NotImplementedError() + + @property + def create_intent(self) -> Callable[ + [gcdc_intent.CreateIntentRequest], + Union[ + gcdc_intent.Intent, + Awaitable[gcdc_intent.Intent] + ]]: + raise NotImplementedError() + + @property + def update_intent(self) -> Callable[ + [gcdc_intent.UpdateIntentRequest], + Union[ + gcdc_intent.Intent, + Awaitable[gcdc_intent.Intent] + ]]: + raise NotImplementedError() + + @property + def delete_intent(self) -> Callable[ + [intent.DeleteIntentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'IntentsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py new file mode 100644 index 00000000..ad4e7391 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py @@ -0,0 +1,374 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +from google.protobuf import empty_pb2 # type: ignore +from .base import IntentsTransport, DEFAULT_CLIENT_INFO + + +class IntentsGrpcTransport(IntentsTransport): + """gRPC backend transport for Intents. + + Service for managing + [Intents][google.cloud.dialogflow.cx.v3.Intent]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_intents(self) -> Callable[ + [intent.ListIntentsRequest], + intent.ListIntentsResponse]: + r"""Return a callable for the list intents method over gRPC. + + Returns the list of all intents in the specified + agent. + + Returns: + Callable[[~.ListIntentsRequest], + ~.ListIntentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_intents' not in self._stubs: + self._stubs['list_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Intents/ListIntents', + request_serializer=intent.ListIntentsRequest.serialize, + response_deserializer=intent.ListIntentsResponse.deserialize, + ) + return self._stubs['list_intents'] + + @property + def get_intent(self) -> Callable[ + [intent.GetIntentRequest], + intent.Intent]: + r"""Return a callable for the get intent method over gRPC. + + Retrieves the specified intent. + + Returns: + Callable[[~.GetIntentRequest], + ~.Intent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_intent' not in self._stubs: + self._stubs['get_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Intents/GetIntent', + request_serializer=intent.GetIntentRequest.serialize, + response_deserializer=intent.Intent.deserialize, + ) + return self._stubs['get_intent'] + + @property + def create_intent(self) -> Callable[ + [gcdc_intent.CreateIntentRequest], + gcdc_intent.Intent]: + r"""Return a callable for the create intent method over gRPC. + + Creates an intent in the specified agent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateIntentRequest], + ~.Intent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_intent' not in self._stubs: + self._stubs['create_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Intents/CreateIntent', + request_serializer=gcdc_intent.CreateIntentRequest.serialize, + response_deserializer=gcdc_intent.Intent.deserialize, + ) + return self._stubs['create_intent'] + + @property + def update_intent(self) -> Callable[ + [gcdc_intent.UpdateIntentRequest], + gcdc_intent.Intent]: + r"""Return a callable for the update intent method over gRPC. + + Updates the specified intent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateIntentRequest], + ~.Intent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_intent' not in self._stubs: + self._stubs['update_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Intents/UpdateIntent', + request_serializer=gcdc_intent.UpdateIntentRequest.serialize, + response_deserializer=gcdc_intent.Intent.deserialize, + ) + return self._stubs['update_intent'] + + @property + def delete_intent(self) -> Callable[ + [intent.DeleteIntentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete intent method over gRPC. + + Deletes the specified intent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteIntentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_intent' not in self._stubs: + self._stubs['delete_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Intents/DeleteIntent', + request_serializer=intent.DeleteIntentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_intent'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'IntentsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py new file mode 100644 index 00000000..6ab30ade --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py @@ -0,0 +1,379 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +from google.protobuf import empty_pb2 # type: ignore +from .base import IntentsTransport, DEFAULT_CLIENT_INFO +from .grpc import IntentsGrpcTransport + + +class IntentsGrpcAsyncIOTransport(IntentsTransport): + """gRPC AsyncIO backend transport for Intents. + + Service for managing + [Intents][google.cloud.dialogflow.cx.v3.Intent]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_intents(self) -> Callable[ + [intent.ListIntentsRequest], + Awaitable[intent.ListIntentsResponse]]: + r"""Return a callable for the list intents method over gRPC. + + Returns the list of all intents in the specified + agent. + + Returns: + Callable[[~.ListIntentsRequest], + Awaitable[~.ListIntentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_intents' not in self._stubs: + self._stubs['list_intents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Intents/ListIntents', + request_serializer=intent.ListIntentsRequest.serialize, + response_deserializer=intent.ListIntentsResponse.deserialize, + ) + return self._stubs['list_intents'] + + @property + def get_intent(self) -> Callable[ + [intent.GetIntentRequest], + Awaitable[intent.Intent]]: + r"""Return a callable for the get intent method over gRPC. + + Retrieves the specified intent. + + Returns: + Callable[[~.GetIntentRequest], + Awaitable[~.Intent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_intent' not in self._stubs: + self._stubs['get_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Intents/GetIntent', + request_serializer=intent.GetIntentRequest.serialize, + response_deserializer=intent.Intent.deserialize, + ) + return self._stubs['get_intent'] + + @property + def create_intent(self) -> Callable[ + [gcdc_intent.CreateIntentRequest], + Awaitable[gcdc_intent.Intent]]: + r"""Return a callable for the create intent method over gRPC. + + Creates an intent in the specified agent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateIntentRequest], + Awaitable[~.Intent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_intent' not in self._stubs: + self._stubs['create_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Intents/CreateIntent', + request_serializer=gcdc_intent.CreateIntentRequest.serialize, + response_deserializer=gcdc_intent.Intent.deserialize, + ) + return self._stubs['create_intent'] + + @property + def update_intent(self) -> Callable[ + [gcdc_intent.UpdateIntentRequest], + Awaitable[gcdc_intent.Intent]]: + r"""Return a callable for the update intent method over gRPC. + + Updates the specified intent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateIntentRequest], + Awaitable[~.Intent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_intent' not in self._stubs: + self._stubs['update_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Intents/UpdateIntent', + request_serializer=gcdc_intent.UpdateIntentRequest.serialize, + response_deserializer=gcdc_intent.Intent.deserialize, + ) + return self._stubs['update_intent'] + + @property + def delete_intent(self) -> Callable[ + [intent.DeleteIntentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete intent method over gRPC. + + Deletes the specified intent. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteIntentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_intent' not in self._stubs: + self._stubs['delete_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Intents/DeleteIntent', + request_serializer=intent.DeleteIntentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_intent'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'IntentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/__init__.py new file mode 100644 index 00000000..b8668f72 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import PagesClient +from .async_client import PagesAsyncClient + +__all__ = ( + 'PagesClient', + 'PagesAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/async_client.py new file mode 100644 index 00000000..212aa81d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/async_client.py @@ -0,0 +1,645 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.pages import pagers +from google.cloud.dialogflowcx_v3.types import fulfillment +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import page as gcdc_page +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport +from .client import PagesClient + + +class PagesAsyncClient: + """Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page].""" + + _client: PagesClient + + DEFAULT_ENDPOINT = PagesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PagesClient.DEFAULT_MTLS_ENDPOINT + + entity_type_path = staticmethod(PagesClient.entity_type_path) + parse_entity_type_path = staticmethod(PagesClient.parse_entity_type_path) + flow_path = staticmethod(PagesClient.flow_path) + parse_flow_path = staticmethod(PagesClient.parse_flow_path) + intent_path = staticmethod(PagesClient.intent_path) + parse_intent_path = staticmethod(PagesClient.parse_intent_path) + page_path = staticmethod(PagesClient.page_path) + parse_page_path = staticmethod(PagesClient.parse_page_path) + transition_route_group_path = staticmethod(PagesClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(PagesClient.parse_transition_route_group_path) + webhook_path = staticmethod(PagesClient.webhook_path) + parse_webhook_path = staticmethod(PagesClient.parse_webhook_path) + common_billing_account_path = staticmethod(PagesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PagesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PagesClient.common_folder_path) + parse_common_folder_path = staticmethod(PagesClient.parse_common_folder_path) + common_organization_path = staticmethod(PagesClient.common_organization_path) + parse_common_organization_path = staticmethod(PagesClient.parse_common_organization_path) + common_project_path = staticmethod(PagesClient.common_project_path) + parse_common_project_path = staticmethod(PagesClient.parse_common_project_path) + common_location_path = staticmethod(PagesClient.common_location_path) + parse_common_location_path = staticmethod(PagesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PagesAsyncClient: The constructed client. + """ + return PagesClient.from_service_account_info.__func__(PagesAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PagesAsyncClient: The constructed client. + """ + return PagesClient.from_service_account_file.__func__(PagesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PagesTransport: + """Returns the transport used by the client instance. + + Returns: + PagesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PagesClient).get_transport_class, type(PagesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PagesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the pages client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PagesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PagesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_pages(self, + request: page.ListPagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPagesAsyncPager: + r"""Returns the list of all pages in the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListPagesRequest`): + The request object. The request message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. + parent (:class:`str`): + Required. The flow to list all pages for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.pages.pagers.ListPagesAsyncPager: + The response message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = page.ListPagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_pages, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPagesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_page(self, + request: page.GetPageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> page.Page: + r"""Retrieves the specified page. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetPageRequest`): + The request object. The request message for + [Pages.GetPage][google.cloud.dialogflow.cx.v3.Pages.GetPage]. + name (:class:`str`): + Required. The name of the page. Format: + ``projects//locations//agents//flows//pages/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = page.GetPageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_page, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_page(self, + request: gcdc_page.CreatePageRequest = None, + *, + parent: str = None, + page: gcdc_page.Page = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_page.Page: + r"""Creates a page in the specified flow. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreatePageRequest`): + The request object. The request message for + [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage]. + parent (:class:`str`): + Required. The flow to create a page for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + page (:class:`google.cloud.dialogflowcx_v3.types.Page`): + Required. The page to create. + This corresponds to the ``page`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, page]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_page.CreatePageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if page is not None: + request.page = page + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_page, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_page(self, + request: gcdc_page.UpdatePageRequest = None, + *, + page: gcdc_page.Page = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_page.Page: + r"""Updates the specified page. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdatePageRequest`): + The request object. The request message for + [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage]. + page (:class:`google.cloud.dialogflowcx_v3.types.Page`): + Required. The page to update. + This corresponds to the ``page`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The mask to control which fields get + updated. If the mask is not present, all + fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([page, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_page.UpdatePageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if page is not None: + request.page = page + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_page, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("page.name", request.page.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_page(self, + request: page.DeletePageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified page. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeletePageRequest`): + The request object. The request message for + [Pages.DeletePage][google.cloud.dialogflow.cx.v3.Pages.DeletePage]. + name (:class:`str`): + Required. The name of the page to delete. Format: + ``projects//locations//agents//Flows//pages/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = page.DeletePageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_page, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PagesAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/client.py new file mode 100644 index 00000000..3b124dc3 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/client.py @@ -0,0 +1,887 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.pages import pagers +from google.cloud.dialogflowcx_v3.types import fulfillment +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import page as gcdc_page +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PagesGrpcTransport +from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport + + +class PagesClientMeta(type): + """Metaclass for the Pages client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[PagesTransport]] + _transport_registry["grpc"] = PagesGrpcTransport + _transport_registry["grpc_asyncio"] = PagesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PagesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class PagesClient(metaclass=PagesClientMeta): + """Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page].""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PagesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PagesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PagesTransport: + """Returns the transport used by the client instance. + + Returns: + PagesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PagesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the pages client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PagesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PagesTransport): + # transport is a PagesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_pages(self, + request: Union[page.ListPagesRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPagesPager: + r"""Returns the list of all pages in the specified flow. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListPagesRequest, dict]): + The request object. The request message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. + parent (str): + Required. The flow to list all pages for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.pages.pagers.ListPagesPager: + The response message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a page.ListPagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, page.ListPagesRequest): + request = page.ListPagesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_pages] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPagesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_page(self, + request: Union[page.GetPageRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> page.Page: + r"""Retrieves the specified page. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetPageRequest, dict]): + The request object. The request message for + [Pages.GetPage][google.cloud.dialogflow.cx.v3.Pages.GetPage]. + name (str): + Required. The name of the page. Format: + ``projects//locations//agents//flows//pages/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a page.GetPageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, page.GetPageRequest): + request = page.GetPageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_page] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_page(self, + request: Union[gcdc_page.CreatePageRequest, dict] = None, + *, + parent: str = None, + page: gcdc_page.Page = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_page.Page: + r"""Creates a page in the specified flow. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreatePageRequest, dict]): + The request object. The request message for + [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage]. + parent (str): + Required. The flow to create a page for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + page (google.cloud.dialogflowcx_v3.types.Page): + Required. The page to create. + This corresponds to the ``page`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, page]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_page.CreatePageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_page.CreatePageRequest): + request = gcdc_page.CreatePageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if page is not None: + request.page = page + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_page] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_page(self, + request: Union[gcdc_page.UpdatePageRequest, dict] = None, + *, + page: gcdc_page.Page = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_page.Page: + r"""Updates the specified page. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdatePageRequest, dict]): + The request object. The request message for + [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage]. + page (google.cloud.dialogflowcx_v3.types.Page): + Required. The page to update. + This corresponds to the ``page`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get + updated. If the mask is not present, all + fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([page, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_page.UpdatePageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_page.UpdatePageRequest): + request = gcdc_page.UpdatePageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if page is not None: + request.page = page + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_page] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("page.name", request.page.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_page(self, + request: Union[page.DeletePageRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified page. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeletePageRequest, dict]): + The request object. The request message for + [Pages.DeletePage][google.cloud.dialogflow.cx.v3.Pages.DeletePage]. + name (str): + Required. The name of the page to delete. Format: + ``projects//locations//agents//Flows//pages/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a page.DeletePageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, page.DeletePageRequest): + request = page.DeletePageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_page] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PagesClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/pagers.py new file mode 100644 index 00000000..e31b21df --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import page + + +class ListPagesPager: + """A pager for iterating through ``list_pages`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListPagesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``pages`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPages`` requests and continue to iterate + through the ``pages`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListPagesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., page.ListPagesResponse], + request: page.ListPagesRequest, + response: page.ListPagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListPagesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListPagesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = page.ListPagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[page.ListPagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[page.Page]: + for page in self.pages: + yield from page.pages + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPagesAsyncPager: + """A pager for iterating through ``list_pages`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListPagesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``pages`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPages`` requests and continue to iterate + through the ``pages`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListPagesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[page.ListPagesResponse]], + request: page.ListPagesRequest, + response: page.ListPagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListPagesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListPagesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = page.ListPagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[page.ListPagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[page.Page]: + async def async_generator(): + async for page in self.pages: + for response in page.pages: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py new file mode 100644 index 00000000..ee74f029 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import PagesTransport +from .grpc import PagesGrpcTransport +from .grpc_asyncio import PagesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PagesTransport]] +_transport_registry['grpc'] = PagesGrpcTransport +_transport_registry['grpc_asyncio'] = PagesGrpcAsyncIOTransport + +__all__ = ( + 'PagesTransport', + 'PagesGrpcTransport', + 'PagesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/base.py new file mode 100644 index 00000000..8453abed --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/base.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import page as gcdc_page +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class PagesTransport(abc.ABC): + """Abstract transport class for Pages.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_pages: gapic_v1.method.wrap_method( + self.list_pages, + default_timeout=None, + client_info=client_info, + ), + self.get_page: gapic_v1.method.wrap_method( + self.get_page, + default_timeout=None, + client_info=client_info, + ), + self.create_page: gapic_v1.method.wrap_method( + self.create_page, + default_timeout=None, + client_info=client_info, + ), + self.update_page: gapic_v1.method.wrap_method( + self.update_page, + default_timeout=None, + client_info=client_info, + ), + self.delete_page: gapic_v1.method.wrap_method( + self.delete_page, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_pages(self) -> Callable[ + [page.ListPagesRequest], + Union[ + page.ListPagesResponse, + Awaitable[page.ListPagesResponse] + ]]: + raise NotImplementedError() + + @property + def get_page(self) -> Callable[ + [page.GetPageRequest], + Union[ + page.Page, + Awaitable[page.Page] + ]]: + raise NotImplementedError() + + @property + def create_page(self) -> Callable[ + [gcdc_page.CreatePageRequest], + Union[ + gcdc_page.Page, + Awaitable[gcdc_page.Page] + ]]: + raise NotImplementedError() + + @property + def update_page(self) -> Callable[ + [gcdc_page.UpdatePageRequest], + Union[ + gcdc_page.Page, + Awaitable[gcdc_page.Page] + ]]: + raise NotImplementedError() + + @property + def delete_page(self) -> Callable[ + [page.DeletePageRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'PagesTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py new file mode 100644 index 00000000..c2eab9f9 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py @@ -0,0 +1,372 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import page as gcdc_page +from google.protobuf import empty_pb2 # type: ignore +from .base import PagesTransport, DEFAULT_CLIENT_INFO + + +class PagesGrpcTransport(PagesTransport): + """gRPC backend transport for Pages. + + Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_pages(self) -> Callable[ + [page.ListPagesRequest], + page.ListPagesResponse]: + r"""Return a callable for the list pages method over gRPC. + + Returns the list of all pages in the specified flow. + + Returns: + Callable[[~.ListPagesRequest], + ~.ListPagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_pages' not in self._stubs: + self._stubs['list_pages'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/ListPages', + request_serializer=page.ListPagesRequest.serialize, + response_deserializer=page.ListPagesResponse.deserialize, + ) + return self._stubs['list_pages'] + + @property + def get_page(self) -> Callable[ + [page.GetPageRequest], + page.Page]: + r"""Return a callable for the get page method over gRPC. + + Retrieves the specified page. + + Returns: + Callable[[~.GetPageRequest], + ~.Page]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_page' not in self._stubs: + self._stubs['get_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/GetPage', + request_serializer=page.GetPageRequest.serialize, + response_deserializer=page.Page.deserialize, + ) + return self._stubs['get_page'] + + @property + def create_page(self) -> Callable[ + [gcdc_page.CreatePageRequest], + gcdc_page.Page]: + r"""Return a callable for the create page method over gRPC. + + Creates a page in the specified flow. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreatePageRequest], + ~.Page]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_page' not in self._stubs: + self._stubs['create_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/CreatePage', + request_serializer=gcdc_page.CreatePageRequest.serialize, + response_deserializer=gcdc_page.Page.deserialize, + ) + return self._stubs['create_page'] + + @property + def update_page(self) -> Callable[ + [gcdc_page.UpdatePageRequest], + gcdc_page.Page]: + r"""Return a callable for the update page method over gRPC. + + Updates the specified page. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdatePageRequest], + ~.Page]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_page' not in self._stubs: + self._stubs['update_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/UpdatePage', + request_serializer=gcdc_page.UpdatePageRequest.serialize, + response_deserializer=gcdc_page.Page.deserialize, + ) + return self._stubs['update_page'] + + @property + def delete_page(self) -> Callable[ + [page.DeletePageRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete page method over gRPC. + + Deletes the specified page. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeletePageRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_page' not in self._stubs: + self._stubs['delete_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/DeletePage', + request_serializer=page.DeletePageRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_page'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'PagesGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py new file mode 100644 index 00000000..acb3988f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py @@ -0,0 +1,377 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import page as gcdc_page +from google.protobuf import empty_pb2 # type: ignore +from .base import PagesTransport, DEFAULT_CLIENT_INFO +from .grpc import PagesGrpcTransport + + +class PagesGrpcAsyncIOTransport(PagesTransport): + """gRPC AsyncIO backend transport for Pages. + + Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_pages(self) -> Callable[ + [page.ListPagesRequest], + Awaitable[page.ListPagesResponse]]: + r"""Return a callable for the list pages method over gRPC. + + Returns the list of all pages in the specified flow. + + Returns: + Callable[[~.ListPagesRequest], + Awaitable[~.ListPagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_pages' not in self._stubs: + self._stubs['list_pages'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/ListPages', + request_serializer=page.ListPagesRequest.serialize, + response_deserializer=page.ListPagesResponse.deserialize, + ) + return self._stubs['list_pages'] + + @property + def get_page(self) -> Callable[ + [page.GetPageRequest], + Awaitable[page.Page]]: + r"""Return a callable for the get page method over gRPC. + + Retrieves the specified page. + + Returns: + Callable[[~.GetPageRequest], + Awaitable[~.Page]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_page' not in self._stubs: + self._stubs['get_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/GetPage', + request_serializer=page.GetPageRequest.serialize, + response_deserializer=page.Page.deserialize, + ) + return self._stubs['get_page'] + + @property + def create_page(self) -> Callable[ + [gcdc_page.CreatePageRequest], + Awaitable[gcdc_page.Page]]: + r"""Return a callable for the create page method over gRPC. + + Creates a page in the specified flow. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreatePageRequest], + Awaitable[~.Page]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_page' not in self._stubs: + self._stubs['create_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/CreatePage', + request_serializer=gcdc_page.CreatePageRequest.serialize, + response_deserializer=gcdc_page.Page.deserialize, + ) + return self._stubs['create_page'] + + @property + def update_page(self) -> Callable[ + [gcdc_page.UpdatePageRequest], + Awaitable[gcdc_page.Page]]: + r"""Return a callable for the update page method over gRPC. + + Updates the specified page. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdatePageRequest], + Awaitable[~.Page]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_page' not in self._stubs: + self._stubs['update_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/UpdatePage', + request_serializer=gcdc_page.UpdatePageRequest.serialize, + response_deserializer=gcdc_page.Page.deserialize, + ) + return self._stubs['update_page'] + + @property + def delete_page(self) -> Callable[ + [page.DeletePageRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete page method over gRPC. + + Deletes the specified page. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeletePageRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_page' not in self._stubs: + self._stubs['delete_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/DeletePage', + request_serializer=page.DeletePageRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_page'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PagesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py new file mode 100644 index 00000000..292d96e7 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SecuritySettingsServiceClient +from .async_client import SecuritySettingsServiceAsyncClient + +__all__ = ( + 'SecuritySettingsServiceClient', + 'SecuritySettingsServiceAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py new file mode 100644 index 00000000..07fa22fd --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py @@ -0,0 +1,592 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.security_settings_service import pagers +from google.cloud.dialogflowcx_v3.types import security_settings +from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport +from .client import SecuritySettingsServiceClient + + +class SecuritySettingsServiceAsyncClient: + """Service for managing security settings for Dialogflow.""" + + _client: SecuritySettingsServiceClient + + DEFAULT_ENDPOINT = SecuritySettingsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecuritySettingsServiceClient.DEFAULT_MTLS_ENDPOINT + + deidentify_template_path = staticmethod(SecuritySettingsServiceClient.deidentify_template_path) + parse_deidentify_template_path = staticmethod(SecuritySettingsServiceClient.parse_deidentify_template_path) + inspect_template_path = staticmethod(SecuritySettingsServiceClient.inspect_template_path) + parse_inspect_template_path = staticmethod(SecuritySettingsServiceClient.parse_inspect_template_path) + security_settings_path = staticmethod(SecuritySettingsServiceClient.security_settings_path) + parse_security_settings_path = staticmethod(SecuritySettingsServiceClient.parse_security_settings_path) + common_billing_account_path = staticmethod(SecuritySettingsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecuritySettingsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecuritySettingsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SecuritySettingsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SecuritySettingsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SecuritySettingsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SecuritySettingsServiceClient.common_project_path) + parse_common_project_path = staticmethod(SecuritySettingsServiceClient.parse_common_project_path) + common_location_path = staticmethod(SecuritySettingsServiceClient.common_location_path) + parse_common_location_path = staticmethod(SecuritySettingsServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SecuritySettingsServiceAsyncClient: The constructed client. + """ + return SecuritySettingsServiceClient.from_service_account_info.__func__(SecuritySettingsServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SecuritySettingsServiceAsyncClient: The constructed client. + """ + return SecuritySettingsServiceClient.from_service_account_file.__func__(SecuritySettingsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SecuritySettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SecuritySettingsServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SecuritySettingsServiceClient).get_transport_class, type(SecuritySettingsServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SecuritySettingsServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security settings service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SecuritySettingsServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SecuritySettingsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_security_settings(self, + request: gcdc_security_settings.CreateSecuritySettingsRequest = None, + *, + parent: str = None, + security_settings: gcdc_security_settings.SecuritySettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Create security settings in the specified location. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.CreateSecuritySettings][]. + parent (:class:`str`): + Required. The location to create an + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_settings (:class:`google.cloud.dialogflowcx_v3.types.SecuritySettings`): + Required. The security settings to + create. + + This corresponds to the ``security_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, security_settings]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_security_settings.CreateSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_settings is not None: + request.security_settings = security_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_security_settings(self, + request: security_settings.GetSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> security_settings.SecuritySettings: + r"""Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings]. + name (:class:`str`): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = security_settings.GetSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_security_settings(self, + request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, + *, + security_settings: gcdc_security_settings.SecuritySettings = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings]. + security_settings (:class:`google.cloud.dialogflowcx_v3.types.SecuritySettings`): + Required. [SecuritySettings] object that contains values + for each of the fields to update. + + This corresponds to the ``security_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_security_settings.UpdateSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_settings is not None: + request.security_settings = security_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_settings.name", request.security_settings.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_security_settings(self, + request: security_settings.ListSecuritySettingsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecuritySettingsAsyncPager: + r"""Returns the list of all security settings in the + specified location. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.ListSecuritySettings][]. + parent (:class:`str`): + Required. The location to list all security settings + for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.security_settings_service.pagers.ListSecuritySettingsAsyncPager: + The response message for + [SecuritySettings.ListSecuritySettings][]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = security_settings.ListSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSecuritySettingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_security_settings(self, + request: security_settings.DeleteSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.DeleteSecuritySettings][]. + name (:class:`str`): + Required. The name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + to delete. Format: + ``projects//locations//securitySettings/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = security_settings.DeleteSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SecuritySettingsServiceAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py new file mode 100644 index 00000000..42a2ac13 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py @@ -0,0 +1,807 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.security_settings_service import pagers +from google.cloud.dialogflowcx_v3.types import security_settings +from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecuritySettingsServiceGrpcTransport +from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport + + +class SecuritySettingsServiceClientMeta(type): + """Metaclass for the SecuritySettingsService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SecuritySettingsServiceTransport]] + _transport_registry["grpc"] = SecuritySettingsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SecuritySettingsServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SecuritySettingsServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SecuritySettingsServiceClient(metaclass=SecuritySettingsServiceClientMeta): + """Service for managing security settings for Dialogflow.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SecuritySettingsServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SecuritySettingsServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SecuritySettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SecuritySettingsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def deidentify_template_path(organization: str,location: str,deidentify_template: str,) -> str: + """Returns a fully-qualified deidentify_template string.""" + return "organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}".format(organization=organization, location=location, deidentify_template=deidentify_template, ) + + @staticmethod + def parse_deidentify_template_path(path: str) -> Dict[str,str]: + """Parses a deidentify_template path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/locations/(?P.+?)/deidentifyTemplates/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def inspect_template_path(organization: str,location: str,inspect_template: str,) -> str: + """Returns a fully-qualified inspect_template string.""" + return "organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}".format(organization=organization, location=location, inspect_template=inspect_template, ) + + @staticmethod + def parse_inspect_template_path(path: str) -> Dict[str,str]: + """Parses a inspect_template path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/locations/(?P.+?)/inspectTemplates/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_settings_path(project: str,location: str,security_settings: str,) -> str: + """Returns a fully-qualified security_settings string.""" + return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + + @staticmethod + def parse_security_settings_path(path: str) -> Dict[str,str]: + """Parses a security_settings path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SecuritySettingsServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security settings service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SecuritySettingsServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SecuritySettingsServiceTransport): + # transport is a SecuritySettingsServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def create_security_settings(self, + request: Union[gcdc_security_settings.CreateSecuritySettingsRequest, dict] = None, + *, + parent: str = None, + security_settings: gcdc_security_settings.SecuritySettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Create security settings in the specified location. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateSecuritySettingsRequest, dict]): + The request object. The request message for + [SecuritySettings.CreateSecuritySettings][]. + parent (str): + Required. The location to create an + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_settings (google.cloud.dialogflowcx_v3.types.SecuritySettings): + Required. The security settings to + create. + + This corresponds to the ``security_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, security_settings]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_security_settings.CreateSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_security_settings.CreateSecuritySettingsRequest): + request = gcdc_security_settings.CreateSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_settings is not None: + request.security_settings = security_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_security_settings(self, + request: Union[security_settings.GetSecuritySettingsRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> security_settings.SecuritySettings: + r"""Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetSecuritySettingsRequest, dict]): + The request object. The request message for + [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings]. + name (str): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a security_settings.GetSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, security_settings.GetSecuritySettingsRequest): + request = security_settings.GetSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_security_settings(self, + request: Union[gcdc_security_settings.UpdateSecuritySettingsRequest, dict] = None, + *, + security_settings: gcdc_security_settings.SecuritySettings = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateSecuritySettingsRequest, dict]): + The request object. The request message for + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings]. + security_settings (google.cloud.dialogflowcx_v3.types.SecuritySettings): + Required. [SecuritySettings] object that contains values + for each of the fields to update. + + This corresponds to the ``security_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_security_settings.UpdateSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_security_settings.UpdateSecuritySettingsRequest): + request = gcdc_security_settings.UpdateSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_settings is not None: + request.security_settings = security_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_settings.name", request.security_settings.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_security_settings(self, + request: Union[security_settings.ListSecuritySettingsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecuritySettingsPager: + r"""Returns the list of all security settings in the + specified location. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest, dict]): + The request object. The request message for + [SecuritySettings.ListSecuritySettings][]. + parent (str): + Required. The location to list all security settings + for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.security_settings_service.pagers.ListSecuritySettingsPager: + The response message for + [SecuritySettings.ListSecuritySettings][]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a security_settings.ListSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, security_settings.ListSecuritySettingsRequest): + request = security_settings.ListSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSecuritySettingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_security_settings(self, + request: Union[security_settings.DeleteSecuritySettingsRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteSecuritySettingsRequest, dict]): + The request object. The request message for + [SecuritySettings.DeleteSecuritySettings][]. + name (str): + Required. The name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + to delete. Format: + ``projects//locations//securitySettings/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a security_settings.DeleteSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, security_settings.DeleteSecuritySettingsRequest): + request = security_settings.DeleteSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SecuritySettingsServiceClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py new file mode 100644 index 00000000..40ee8ae8 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import security_settings + + +class ListSecuritySettingsPager: + """A pager for iterating through ``list_security_settings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``security_settings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSecuritySettings`` requests and continue to iterate + through the ``security_settings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., security_settings.ListSecuritySettingsResponse], + request: security_settings.ListSecuritySettingsRequest, + response: security_settings.ListSecuritySettingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = security_settings.ListSecuritySettingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[security_settings.ListSecuritySettingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[security_settings.SecuritySettings]: + for page in self.pages: + yield from page.security_settings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSecuritySettingsAsyncPager: + """A pager for iterating through ``list_security_settings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``security_settings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSecuritySettings`` requests and continue to iterate + through the ``security_settings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[security_settings.ListSecuritySettingsResponse]], + request: security_settings.ListSecuritySettingsRequest, + response: security_settings.ListSecuritySettingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = security_settings.ListSecuritySettingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[security_settings.ListSecuritySettingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[security_settings.SecuritySettings]: + async def async_generator(): + async for page in self.pages: + for response in page.security_settings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py new file mode 100644 index 00000000..116b7680 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SecuritySettingsServiceTransport +from .grpc import SecuritySettingsServiceGrpcTransport +from .grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecuritySettingsServiceTransport]] +_transport_registry['grpc'] = SecuritySettingsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SecuritySettingsServiceGrpcAsyncIOTransport + +__all__ = ( + 'SecuritySettingsServiceTransport', + 'SecuritySettingsServiceGrpcTransport', + 'SecuritySettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py new file mode 100644 index 00000000..677b2eb0 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import security_settings +from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class SecuritySettingsServiceTransport(abc.ABC): + """Abstract transport class for SecuritySettingsService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_security_settings: gapic_v1.method.wrap_method( + self.create_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_security_settings: gapic_v1.method.wrap_method( + self.get_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_security_settings: gapic_v1.method.wrap_method( + self.update_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.list_security_settings: gapic_v1.method.wrap_method( + self.list_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.delete_security_settings: gapic_v1.method.wrap_method( + self.delete_security_settings, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_security_settings(self) -> Callable[ + [gcdc_security_settings.CreateSecuritySettingsRequest], + Union[ + gcdc_security_settings.SecuritySettings, + Awaitable[gcdc_security_settings.SecuritySettings] + ]]: + raise NotImplementedError() + + @property + def get_security_settings(self) -> Callable[ + [security_settings.GetSecuritySettingsRequest], + Union[ + security_settings.SecuritySettings, + Awaitable[security_settings.SecuritySettings] + ]]: + raise NotImplementedError() + + @property + def update_security_settings(self) -> Callable[ + [gcdc_security_settings.UpdateSecuritySettingsRequest], + Union[ + gcdc_security_settings.SecuritySettings, + Awaitable[gcdc_security_settings.SecuritySettings] + ]]: + raise NotImplementedError() + + @property + def list_security_settings(self) -> Callable[ + [security_settings.ListSecuritySettingsRequest], + Union[ + security_settings.ListSecuritySettingsResponse, + Awaitable[security_settings.ListSecuritySettingsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_security_settings(self) -> Callable[ + [security_settings.DeleteSecuritySettingsRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SecuritySettingsServiceTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py new file mode 100644 index 00000000..d133ec0c --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py @@ -0,0 +1,365 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import security_settings +from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings +from google.protobuf import empty_pb2 # type: ignore +from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO + + +class SecuritySettingsServiceGrpcTransport(SecuritySettingsServiceTransport): + """gRPC backend transport for SecuritySettingsService. + + Service for managing security settings for Dialogflow. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_security_settings(self) -> Callable[ + [gcdc_security_settings.CreateSecuritySettingsRequest], + gcdc_security_settings.SecuritySettings]: + r"""Return a callable for the create security settings method over gRPC. + + Create security settings in the specified location. + + Returns: + Callable[[~.CreateSecuritySettingsRequest], + ~.SecuritySettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_security_settings' not in self._stubs: + self._stubs['create_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/CreateSecuritySettings', + request_serializer=gcdc_security_settings.CreateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs['create_security_settings'] + + @property + def get_security_settings(self) -> Callable[ + [security_settings.GetSecuritySettingsRequest], + security_settings.SecuritySettings]: + r"""Return a callable for the get security settings method over gRPC. + + Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Returns: + Callable[[~.GetSecuritySettingsRequest], + ~.SecuritySettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_security_settings' not in self._stubs: + self._stubs['get_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/GetSecuritySettings', + request_serializer=security_settings.GetSecuritySettingsRequest.serialize, + response_deserializer=security_settings.SecuritySettings.deserialize, + ) + return self._stubs['get_security_settings'] + + @property + def update_security_settings(self) -> Callable[ + [gcdc_security_settings.UpdateSecuritySettingsRequest], + gcdc_security_settings.SecuritySettings]: + r"""Return a callable for the update security settings method over gRPC. + + Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Returns: + Callable[[~.UpdateSecuritySettingsRequest], + ~.SecuritySettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_security_settings' not in self._stubs: + self._stubs['update_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/UpdateSecuritySettings', + request_serializer=gcdc_security_settings.UpdateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs['update_security_settings'] + + @property + def list_security_settings(self) -> Callable[ + [security_settings.ListSecuritySettingsRequest], + security_settings.ListSecuritySettingsResponse]: + r"""Return a callable for the list security settings method over gRPC. + + Returns the list of all security settings in the + specified location. + + Returns: + Callable[[~.ListSecuritySettingsRequest], + ~.ListSecuritySettingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_security_settings' not in self._stubs: + self._stubs['list_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/ListSecuritySettings', + request_serializer=security_settings.ListSecuritySettingsRequest.serialize, + response_deserializer=security_settings.ListSecuritySettingsResponse.deserialize, + ) + return self._stubs['list_security_settings'] + + @property + def delete_security_settings(self) -> Callable[ + [security_settings.DeleteSecuritySettingsRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete security settings method over gRPC. + + Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Returns: + Callable[[~.DeleteSecuritySettingsRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_security_settings' not in self._stubs: + self._stubs['delete_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/DeleteSecuritySettings', + request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_security_settings'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'SecuritySettingsServiceGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..ebed7724 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py @@ -0,0 +1,370 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import security_settings +from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings +from google.protobuf import empty_pb2 # type: ignore +from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SecuritySettingsServiceGrpcTransport + + +class SecuritySettingsServiceGrpcAsyncIOTransport(SecuritySettingsServiceTransport): + """gRPC AsyncIO backend transport for SecuritySettingsService. + + Service for managing security settings for Dialogflow. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_security_settings(self) -> Callable[ + [gcdc_security_settings.CreateSecuritySettingsRequest], + Awaitable[gcdc_security_settings.SecuritySettings]]: + r"""Return a callable for the create security settings method over gRPC. + + Create security settings in the specified location. + + Returns: + Callable[[~.CreateSecuritySettingsRequest], + Awaitable[~.SecuritySettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_security_settings' not in self._stubs: + self._stubs['create_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/CreateSecuritySettings', + request_serializer=gcdc_security_settings.CreateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs['create_security_settings'] + + @property + def get_security_settings(self) -> Callable[ + [security_settings.GetSecuritySettingsRequest], + Awaitable[security_settings.SecuritySettings]]: + r"""Return a callable for the get security settings method over gRPC. + + Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Returns: + Callable[[~.GetSecuritySettingsRequest], + Awaitable[~.SecuritySettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_security_settings' not in self._stubs: + self._stubs['get_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/GetSecuritySettings', + request_serializer=security_settings.GetSecuritySettingsRequest.serialize, + response_deserializer=security_settings.SecuritySettings.deserialize, + ) + return self._stubs['get_security_settings'] + + @property + def update_security_settings(self) -> Callable[ + [gcdc_security_settings.UpdateSecuritySettingsRequest], + Awaitable[gcdc_security_settings.SecuritySettings]]: + r"""Return a callable for the update security settings method over gRPC. + + Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Returns: + Callable[[~.UpdateSecuritySettingsRequest], + Awaitable[~.SecuritySettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_security_settings' not in self._stubs: + self._stubs['update_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/UpdateSecuritySettings', + request_serializer=gcdc_security_settings.UpdateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs['update_security_settings'] + + @property + def list_security_settings(self) -> Callable[ + [security_settings.ListSecuritySettingsRequest], + Awaitable[security_settings.ListSecuritySettingsResponse]]: + r"""Return a callable for the list security settings method over gRPC. + + Returns the list of all security settings in the + specified location. + + Returns: + Callable[[~.ListSecuritySettingsRequest], + Awaitable[~.ListSecuritySettingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_security_settings' not in self._stubs: + self._stubs['list_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/ListSecuritySettings', + request_serializer=security_settings.ListSecuritySettingsRequest.serialize, + response_deserializer=security_settings.ListSecuritySettingsResponse.deserialize, + ) + return self._stubs['list_security_settings'] + + @property + def delete_security_settings(self) -> Callable[ + [security_settings.DeleteSecuritySettingsRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete security settings method over gRPC. + + Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Returns: + Callable[[~.DeleteSecuritySettingsRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_security_settings' not in self._stubs: + self._stubs['delete_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/DeleteSecuritySettings', + request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_security_settings'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SecuritySettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py new file mode 100644 index 00000000..fb6678b1 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SessionEntityTypesClient +from .async_client import SessionEntityTypesAsyncClient + +__all__ = ( + 'SessionEntityTypesClient', + 'SessionEntityTypesAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py new file mode 100644 index 00000000..c1d2d662 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py @@ -0,0 +1,634 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.session_entity_types import pagers +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport +from .client import SessionEntityTypesClient + + +class SessionEntityTypesAsyncClient: + """Service for managing + [SessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityType]. + """ + + _client: SessionEntityTypesClient + + DEFAULT_ENDPOINT = SessionEntityTypesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SessionEntityTypesClient.DEFAULT_MTLS_ENDPOINT + + session_entity_type_path = staticmethod(SessionEntityTypesClient.session_entity_type_path) + parse_session_entity_type_path = staticmethod(SessionEntityTypesClient.parse_session_entity_type_path) + common_billing_account_path = staticmethod(SessionEntityTypesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SessionEntityTypesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SessionEntityTypesClient.common_folder_path) + parse_common_folder_path = staticmethod(SessionEntityTypesClient.parse_common_folder_path) + common_organization_path = staticmethod(SessionEntityTypesClient.common_organization_path) + parse_common_organization_path = staticmethod(SessionEntityTypesClient.parse_common_organization_path) + common_project_path = staticmethod(SessionEntityTypesClient.common_project_path) + parse_common_project_path = staticmethod(SessionEntityTypesClient.parse_common_project_path) + common_location_path = staticmethod(SessionEntityTypesClient.common_location_path) + parse_common_location_path = staticmethod(SessionEntityTypesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionEntityTypesAsyncClient: The constructed client. + """ + return SessionEntityTypesClient.from_service_account_info.__func__(SessionEntityTypesAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionEntityTypesAsyncClient: The constructed client. + """ + return SessionEntityTypesClient.from_service_account_file.__func__(SessionEntityTypesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SessionEntityTypesTransport: + """Returns the transport used by the client instance. + + Returns: + SessionEntityTypesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SessionEntityTypesClient).get_transport_class, type(SessionEntityTypesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the session entity types client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SessionEntityTypesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SessionEntityTypesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_session_entity_types(self, + request: session_entity_type.ListSessionEntityTypesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSessionEntityTypesAsyncPager: + r"""Returns the list of all session entity types in the + specified session. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest`): + The request object. The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. + parent (:class:`str`): + Required. The session to list all session entity types + from. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager: + The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = session_entity_type.ListSessionEntityTypesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_session_entity_types, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSessionEntityTypesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_session_entity_type(self, + request: session_entity_type.GetSessionEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session_entity_type.SessionEntityType: + r"""Retrieves the specified session entity type. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetSessionEntityTypeRequest`): + The request object. The request message for + [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.GetSessionEntityType]. + name (:class:`str`): + Required. The name of the session entity type. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at + the user session level (we refer to the entity types + defined at the agent level as "custom entity types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = session_entity_type.GetSessionEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_session_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_session_entity_type(self, + request: gcdc_session_entity_type.CreateSessionEntityTypeRequest = None, + *, + parent: str = None, + session_entity_type: gcdc_session_entity_type.SessionEntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_session_entity_type.SessionEntityType: + r"""Creates a session entity type. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest`): + The request object. The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType]. + parent (:class:`str`): + Required. The session to create a session entity type + for. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + session_entity_type (:class:`google.cloud.dialogflowcx_v3.types.SessionEntityType`): + Required. The session entity type to + create. + + This corresponds to the ``session_entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at + the user session level (we refer to the entity types + defined at the agent level as "custom entity types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, session_entity_type]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_session_entity_type.CreateSessionEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if session_entity_type is not None: + request.session_entity_type = session_entity_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_session_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_session_entity_type(self, + request: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, + *, + session_entity_type: gcdc_session_entity_type.SessionEntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_session_entity_type.SessionEntityType: + r"""Updates the specified session entity type. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateSessionEntityTypeRequest`): + The request object. The request message for + [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.UpdateSessionEntityType]. + session_entity_type (:class:`google.cloud.dialogflowcx_v3.types.SessionEntityType`): + Required. The session entity type to update. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``session_entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The mask to control which fields get + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at + the user session level (we refer to the entity types + defined at the agent level as "custom entity types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([session_entity_type, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_session_entity_type.UpdateSessionEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session_entity_type is not None: + request.session_entity_type = session_entity_type + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_session_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("session_entity_type.name", request.session_entity_type.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_session_entity_type(self, + request: session_entity_type.DeleteSessionEntityTypeRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified session entity type. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteSessionEntityTypeRequest`): + The request object. The request message for + [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.DeleteSessionEntityType]. + name (:class:`str`): + Required. The name of the session entity type to delete. + Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = session_entity_type.DeleteSessionEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_session_entity_type, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionEntityTypesAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py new file mode 100644 index 00000000..edfeef88 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py @@ -0,0 +1,831 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.session_entity_types import pagers +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SessionEntityTypesGrpcTransport +from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport + + +class SessionEntityTypesClientMeta(type): + """Metaclass for the SessionEntityTypes client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SessionEntityTypesTransport]] + _transport_registry["grpc"] = SessionEntityTypesGrpcTransport + _transport_registry["grpc_asyncio"] = SessionEntityTypesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SessionEntityTypesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SessionEntityTypesClient(metaclass=SessionEntityTypesClientMeta): + """Service for managing + [SessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityType]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionEntityTypesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionEntityTypesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SessionEntityTypesTransport: + """Returns the transport used by the client instance. + + Returns: + SessionEntityTypesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def session_entity_type_path(project: str,location: str,agent: str,session: str,entity_type: str,) -> str: + """Returns a fully-qualified session_entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, session=session, entity_type=entity_type, ) + + @staticmethod + def parse_session_entity_type_path(path: str) -> Dict[str,str]: + """Parses a session_entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SessionEntityTypesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the session entity types client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SessionEntityTypesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SessionEntityTypesTransport): + # transport is a SessionEntityTypesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_session_entity_types(self, + request: Union[session_entity_type.ListSessionEntityTypesRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSessionEntityTypesPager: + r"""Returns the list of all session entity types in the + specified session. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest, dict]): + The request object. The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. + parent (str): + Required. The session to list all session entity types + from. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.session_entity_types.pagers.ListSessionEntityTypesPager: + The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a session_entity_type.ListSessionEntityTypesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session_entity_type.ListSessionEntityTypesRequest): + request = session_entity_type.ListSessionEntityTypesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_session_entity_types] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSessionEntityTypesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_session_entity_type(self, + request: Union[session_entity_type.GetSessionEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session_entity_type.SessionEntityType: + r"""Retrieves the specified session entity type. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.GetSessionEntityType]. + name (str): + Required. The name of the session entity type. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at + the user session level (we refer to the entity types + defined at the agent level as "custom entity types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a session_entity_type.GetSessionEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session_entity_type.GetSessionEntityTypeRequest): + request = session_entity_type.GetSessionEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_session_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_session_entity_type(self, + request: Union[gcdc_session_entity_type.CreateSessionEntityTypeRequest, dict] = None, + *, + parent: str = None, + session_entity_type: gcdc_session_entity_type.SessionEntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_session_entity_type.SessionEntityType: + r"""Creates a session entity type. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType]. + parent (str): + Required. The session to create a session entity type + for. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + session_entity_type (google.cloud.dialogflowcx_v3.types.SessionEntityType): + Required. The session entity type to + create. + + This corresponds to the ``session_entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at + the user session level (we refer to the entity types + defined at the agent level as "custom entity types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, session_entity_type]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_session_entity_type.CreateSessionEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_session_entity_type.CreateSessionEntityTypeRequest): + request = gcdc_session_entity_type.CreateSessionEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if session_entity_type is not None: + request.session_entity_type = session_entity_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_session_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_session_entity_type(self, + request: Union[gcdc_session_entity_type.UpdateSessionEntityTypeRequest, dict] = None, + *, + session_entity_type: gcdc_session_entity_type.SessionEntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_session_entity_type.SessionEntityType: + r"""Updates the specified session entity type. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.UpdateSessionEntityType]. + session_entity_type (google.cloud.dialogflowcx_v3.types.SessionEntityType): + Required. The session entity type to update. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``session_entity_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at + the user session level (we refer to the entity types + defined at the agent level as "custom entity types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ https://cloud.google.com/dialogflow/docs/entities-overview). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([session_entity_type, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_session_entity_type.UpdateSessionEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_session_entity_type.UpdateSessionEntityTypeRequest): + request = gcdc_session_entity_type.UpdateSessionEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session_entity_type is not None: + request.session_entity_type = session_entity_type + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_session_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("session_entity_type.name", request.session_entity_type.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_session_entity_type(self, + request: Union[session_entity_type.DeleteSessionEntityTypeRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified session entity type. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteSessionEntityTypeRequest, dict]): + The request object. The request message for + [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.DeleteSessionEntityType]. + name (str): + Required. The name of the session entity type to delete. + Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a session_entity_type.DeleteSessionEntityTypeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session_entity_type.DeleteSessionEntityTypeRequest): + request = session_entity_type.DeleteSessionEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_session_entity_type] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionEntityTypesClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py new file mode 100644 index 00000000..286ee01b --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import session_entity_type + + +class ListSessionEntityTypesPager: + """A pager for iterating through ``list_session_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``session_entity_types`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSessionEntityTypes`` requests and continue to iterate + through the ``session_entity_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., session_entity_type.ListSessionEntityTypesResponse], + request: session_entity_type.ListSessionEntityTypesRequest, + response: session_entity_type.ListSessionEntityTypesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = session_entity_type.ListSessionEntityTypesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[session_entity_type.ListSessionEntityTypesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[session_entity_type.SessionEntityType]: + for page in self.pages: + yield from page.session_entity_types + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSessionEntityTypesAsyncPager: + """A pager for iterating through ``list_session_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``session_entity_types`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSessionEntityTypes`` requests and continue to iterate + through the ``session_entity_types`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[session_entity_type.ListSessionEntityTypesResponse]], + request: session_entity_type.ListSessionEntityTypesRequest, + response: session_entity_type.ListSessionEntityTypesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = session_entity_type.ListSessionEntityTypesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[session_entity_type.ListSessionEntityTypesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[session_entity_type.SessionEntityType]: + async def async_generator(): + async for page in self.pages: + for response in page.session_entity_types: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py new file mode 100644 index 00000000..fee52672 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SessionEntityTypesTransport +from .grpc import SessionEntityTypesGrpcTransport +from .grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SessionEntityTypesTransport]] +_transport_registry['grpc'] = SessionEntityTypesGrpcTransport +_transport_registry['grpc_asyncio'] = SessionEntityTypesGrpcAsyncIOTransport + +__all__ = ( + 'SessionEntityTypesTransport', + 'SessionEntityTypesGrpcTransport', + 'SessionEntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py new file mode 100644 index 00000000..15cab116 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import session_entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class SessionEntityTypesTransport(abc.ABC): + """Abstract transport class for SessionEntityTypes.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_session_entity_types: gapic_v1.method.wrap_method( + self.list_session_entity_types, + default_timeout=None, + client_info=client_info, + ), + self.get_session_entity_type: gapic_v1.method.wrap_method( + self.get_session_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.create_session_entity_type: gapic_v1.method.wrap_method( + self.create_session_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.update_session_entity_type: gapic_v1.method.wrap_method( + self.update_session_entity_type, + default_timeout=None, + client_info=client_info, + ), + self.delete_session_entity_type: gapic_v1.method.wrap_method( + self.delete_session_entity_type, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_session_entity_types(self) -> Callable[ + [session_entity_type.ListSessionEntityTypesRequest], + Union[ + session_entity_type.ListSessionEntityTypesResponse, + Awaitable[session_entity_type.ListSessionEntityTypesResponse] + ]]: + raise NotImplementedError() + + @property + def get_session_entity_type(self) -> Callable[ + [session_entity_type.GetSessionEntityTypeRequest], + Union[ + session_entity_type.SessionEntityType, + Awaitable[session_entity_type.SessionEntityType] + ]]: + raise NotImplementedError() + + @property + def create_session_entity_type(self) -> Callable[ + [gcdc_session_entity_type.CreateSessionEntityTypeRequest], + Union[ + gcdc_session_entity_type.SessionEntityType, + Awaitable[gcdc_session_entity_type.SessionEntityType] + ]]: + raise NotImplementedError() + + @property + def update_session_entity_type(self) -> Callable[ + [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], + Union[ + gcdc_session_entity_type.SessionEntityType, + Awaitable[gcdc_session_entity_type.SessionEntityType] + ]]: + raise NotImplementedError() + + @property + def delete_session_entity_type(self) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SessionEntityTypesTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py new file mode 100644 index 00000000..b3f182b0 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import session_entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type +from google.protobuf import empty_pb2 # type: ignore +from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO + + +class SessionEntityTypesGrpcTransport(SessionEntityTypesTransport): + """gRPC backend transport for SessionEntityTypes. + + Service for managing + [SessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityType]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_session_entity_types(self) -> Callable[ + [session_entity_type.ListSessionEntityTypesRequest], + session_entity_type.ListSessionEntityTypesResponse]: + r"""Return a callable for the list session entity types method over gRPC. + + Returns the list of all session entity types in the + specified session. + + Returns: + Callable[[~.ListSessionEntityTypesRequest], + ~.ListSessionEntityTypesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_session_entity_types' not in self._stubs: + self._stubs['list_session_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SessionEntityTypes/ListSessionEntityTypes', + request_serializer=session_entity_type.ListSessionEntityTypesRequest.serialize, + response_deserializer=session_entity_type.ListSessionEntityTypesResponse.deserialize, + ) + return self._stubs['list_session_entity_types'] + + @property + def get_session_entity_type(self) -> Callable[ + [session_entity_type.GetSessionEntityTypeRequest], + session_entity_type.SessionEntityType]: + r"""Return a callable for the get session entity type method over gRPC. + + Retrieves the specified session entity type. + + Returns: + Callable[[~.GetSessionEntityTypeRequest], + ~.SessionEntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_session_entity_type' not in self._stubs: + self._stubs['get_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SessionEntityTypes/GetSessionEntityType', + request_serializer=session_entity_type.GetSessionEntityTypeRequest.serialize, + response_deserializer=session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['get_session_entity_type'] + + @property + def create_session_entity_type(self) -> Callable[ + [gcdc_session_entity_type.CreateSessionEntityTypeRequest], + gcdc_session_entity_type.SessionEntityType]: + r"""Return a callable for the create session entity type method over gRPC. + + Creates a session entity type. + + Returns: + Callable[[~.CreateSessionEntityTypeRequest], + ~.SessionEntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_session_entity_type' not in self._stubs: + self._stubs['create_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SessionEntityTypes/CreateSessionEntityType', + request_serializer=gcdc_session_entity_type.CreateSessionEntityTypeRequest.serialize, + response_deserializer=gcdc_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['create_session_entity_type'] + + @property + def update_session_entity_type(self) -> Callable[ + [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], + gcdc_session_entity_type.SessionEntityType]: + r"""Return a callable for the update session entity type method over gRPC. + + Updates the specified session entity type. + + Returns: + Callable[[~.UpdateSessionEntityTypeRequest], + ~.SessionEntityType]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_session_entity_type' not in self._stubs: + self._stubs['update_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SessionEntityTypes/UpdateSessionEntityType', + request_serializer=gcdc_session_entity_type.UpdateSessionEntityTypeRequest.serialize, + response_deserializer=gcdc_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['update_session_entity_type'] + + @property + def delete_session_entity_type(self) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete session entity type method over gRPC. + + Deletes the specified session entity type. + + Returns: + Callable[[~.DeleteSessionEntityTypeRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_session_entity_type' not in self._stubs: + self._stubs['delete_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SessionEntityTypes/DeleteSessionEntityType', + request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_session_entity_type'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'SessionEntityTypesGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py new file mode 100644 index 00000000..7788b1d2 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py @@ -0,0 +1,367 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import session_entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type +from google.protobuf import empty_pb2 # type: ignore +from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO +from .grpc import SessionEntityTypesGrpcTransport + + +class SessionEntityTypesGrpcAsyncIOTransport(SessionEntityTypesTransport): + """gRPC AsyncIO backend transport for SessionEntityTypes. + + Service for managing + [SessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityType]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_session_entity_types(self) -> Callable[ + [session_entity_type.ListSessionEntityTypesRequest], + Awaitable[session_entity_type.ListSessionEntityTypesResponse]]: + r"""Return a callable for the list session entity types method over gRPC. + + Returns the list of all session entity types in the + specified session. + + Returns: + Callable[[~.ListSessionEntityTypesRequest], + Awaitable[~.ListSessionEntityTypesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_session_entity_types' not in self._stubs: + self._stubs['list_session_entity_types'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SessionEntityTypes/ListSessionEntityTypes', + request_serializer=session_entity_type.ListSessionEntityTypesRequest.serialize, + response_deserializer=session_entity_type.ListSessionEntityTypesResponse.deserialize, + ) + return self._stubs['list_session_entity_types'] + + @property + def get_session_entity_type(self) -> Callable[ + [session_entity_type.GetSessionEntityTypeRequest], + Awaitable[session_entity_type.SessionEntityType]]: + r"""Return a callable for the get session entity type method over gRPC. + + Retrieves the specified session entity type. + + Returns: + Callable[[~.GetSessionEntityTypeRequest], + Awaitable[~.SessionEntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_session_entity_type' not in self._stubs: + self._stubs['get_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SessionEntityTypes/GetSessionEntityType', + request_serializer=session_entity_type.GetSessionEntityTypeRequest.serialize, + response_deserializer=session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['get_session_entity_type'] + + @property + def create_session_entity_type(self) -> Callable[ + [gcdc_session_entity_type.CreateSessionEntityTypeRequest], + Awaitable[gcdc_session_entity_type.SessionEntityType]]: + r"""Return a callable for the create session entity type method over gRPC. + + Creates a session entity type. + + Returns: + Callable[[~.CreateSessionEntityTypeRequest], + Awaitable[~.SessionEntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_session_entity_type' not in self._stubs: + self._stubs['create_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SessionEntityTypes/CreateSessionEntityType', + request_serializer=gcdc_session_entity_type.CreateSessionEntityTypeRequest.serialize, + response_deserializer=gcdc_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['create_session_entity_type'] + + @property + def update_session_entity_type(self) -> Callable[ + [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], + Awaitable[gcdc_session_entity_type.SessionEntityType]]: + r"""Return a callable for the update session entity type method over gRPC. + + Updates the specified session entity type. + + Returns: + Callable[[~.UpdateSessionEntityTypeRequest], + Awaitable[~.SessionEntityType]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_session_entity_type' not in self._stubs: + self._stubs['update_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SessionEntityTypes/UpdateSessionEntityType', + request_serializer=gcdc_session_entity_type.UpdateSessionEntityTypeRequest.serialize, + response_deserializer=gcdc_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['update_session_entity_type'] + + @property + def delete_session_entity_type(self) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete session entity type method over gRPC. + + Deletes the specified session entity type. + + Returns: + Callable[[~.DeleteSessionEntityTypeRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_session_entity_type' not in self._stubs: + self._stubs['delete_session_entity_type'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SessionEntityTypes/DeleteSessionEntityType', + request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_session_entity_type'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SessionEntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/__init__.py new file mode 100644 index 00000000..92490cc5 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SessionsClient +from .async_client import SessionsAsyncClient + +__all__ = ( + 'SessionsClient', + 'SessionsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/async_client.py new file mode 100644 index 00000000..1d48f757 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/async_client.py @@ -0,0 +1,464 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import audio_config +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import session +from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport +from .client import SessionsClient + + +class SessionsAsyncClient: + """A session represents an interaction with a user. You retrieve user + input and pass it to the + [DetectIntent][google.cloud.dialogflow.cx.v3.Sessions.DetectIntent] + method to determine user intent and respond. + """ + + _client: SessionsClient + + DEFAULT_ENDPOINT = SessionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SessionsClient.DEFAULT_MTLS_ENDPOINT + + entity_type_path = staticmethod(SessionsClient.entity_type_path) + parse_entity_type_path = staticmethod(SessionsClient.parse_entity_type_path) + flow_path = staticmethod(SessionsClient.flow_path) + parse_flow_path = staticmethod(SessionsClient.parse_flow_path) + intent_path = staticmethod(SessionsClient.intent_path) + parse_intent_path = staticmethod(SessionsClient.parse_intent_path) + page_path = staticmethod(SessionsClient.page_path) + parse_page_path = staticmethod(SessionsClient.parse_page_path) + session_path = staticmethod(SessionsClient.session_path) + parse_session_path = staticmethod(SessionsClient.parse_session_path) + session_entity_type_path = staticmethod(SessionsClient.session_entity_type_path) + parse_session_entity_type_path = staticmethod(SessionsClient.parse_session_entity_type_path) + transition_route_group_path = staticmethod(SessionsClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(SessionsClient.parse_transition_route_group_path) + version_path = staticmethod(SessionsClient.version_path) + parse_version_path = staticmethod(SessionsClient.parse_version_path) + webhook_path = staticmethod(SessionsClient.webhook_path) + parse_webhook_path = staticmethod(SessionsClient.parse_webhook_path) + common_billing_account_path = staticmethod(SessionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SessionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SessionsClient.common_folder_path) + parse_common_folder_path = staticmethod(SessionsClient.parse_common_folder_path) + common_organization_path = staticmethod(SessionsClient.common_organization_path) + parse_common_organization_path = staticmethod(SessionsClient.parse_common_organization_path) + common_project_path = staticmethod(SessionsClient.common_project_path) + parse_common_project_path = staticmethod(SessionsClient.parse_common_project_path) + common_location_path = staticmethod(SessionsClient.common_location_path) + parse_common_location_path = staticmethod(SessionsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionsAsyncClient: The constructed client. + """ + return SessionsClient.from_service_account_info.__func__(SessionsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionsAsyncClient: The constructed client. + """ + return SessionsClient.from_service_account_file.__func__(SessionsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SessionsTransport: + """Returns the transport used by the client instance. + + Returns: + SessionsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SessionsClient).get_transport_class, type(SessionsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SessionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sessions client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SessionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SessionsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def detect_intent(self, + request: session.DetectIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.DetectIntentResponse: + r"""Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause session entity types to be updated, which + in turn might affect results of future queries. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DetectIntentRequest`): + The request object. The request to detect user's intent. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.DetectIntentResponse: + The message returned from the + DetectIntent method. + + """ + # Create or coerce a protobuf request object. + request = session.DetectIntentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.detect_intent, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, + ), + default_timeout=220.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("session", request.session), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def streaming_detect_intent(self, + requests: AsyncIterator[session.StreamingDetectIntentRequest] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[session.StreamingDetectIntentResponse]]: + r"""Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + requests (AsyncIterator[`google.cloud.dialogflowcx_v3.types.StreamingDetectIntentRequest`]): + The request object AsyncIterator. The top-level message sent by the + client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent] + method. + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.output_audio_config]. + 2. If + [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio.config][google.cloud.dialogflow.cx.v3.AudioInput.config], + all subsequent messages must contain + [query_input.audio.audio][google.cloud.dialogflow.cx.v3.AudioInput.audio] + to continue with Speech recognition. + If you decide to rather detect an intent from text + input after you already started Speech recognition, + please send a message with + [query_input.text][google.cloud.dialogflow.cx.v3.QueryInput.text]. + However, note that: + + * Dialogflow will bill you for the audio duration so + far. * Dialogflow discards all Speech recognition + results in favor of the input text. + * Dialogflow will use the language code from the + first message. + After you sent all input, you must half-close or abort + the request stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentResponse]: + The top-level message returned from the + StreamingDetectIntent method. + + Multiple response messages can be returned in order: + + 1. If the input was set to streaming audio, the first + one or more messages contain recognition_result. + Each recognition_result represents a more complete + transcript of what the user said. The last + recognition_result has is_final set to true. + 2. If enable_partial_response is true, the following + N messages (currently 1 <= N <= 4) contain + detect_intent_response. The first (N-1) + detect_intent_responses will have response_type + set to PARTIAL. The last detect_intent_response + has response_type set to FINAL. If response_type + is false, response stream only contains the final + detect_intent_response. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.streaming_detect_intent, + default_timeout=220.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def match_intent(self, + request: session.MatchIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.MatchIntentResponse: + r"""Returns preliminary intent match results, doesn't + change the session status. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.MatchIntentRequest`): + The request object. Request of [MatchIntent][]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.MatchIntentResponse: + Response of [MatchIntent][]. + """ + # Create or coerce a protobuf request object. + request = session.MatchIntentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.match_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("session", request.session), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def fulfill_intent(self, + request: session.FulfillIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.FulfillIntentResponse: + r"""Fulfills a matched intent returned by + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent]. + Must be called after + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent], + with input from + [MatchIntentResponse][google.cloud.dialogflow.cx.v3.MatchIntentResponse]. + Otherwise, the behavior is undefined. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.FulfillIntentRequest`): + The request object. Request of [FulfillIntent][] + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.FulfillIntentResponse: + Response of [FulfillIntent][] + """ + # Create or coerce a protobuf request object. + request = session.FulfillIntentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.fulfill_intent, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("match_intent_request.session", request.match_intent_request.session), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/client.py new file mode 100644 index 00000000..7f4f193e --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/client.py @@ -0,0 +1,726 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import audio_config +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import session +from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SessionsGrpcTransport +from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport + + +class SessionsClientMeta(type): + """Metaclass for the Sessions client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[SessionsTransport]] + _transport_registry["grpc"] = SessionsGrpcTransport + _transport_registry["grpc_asyncio"] = SessionsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SessionsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SessionsClient(metaclass=SessionsClientMeta): + """A session represents an interaction with a user. You retrieve user + input and pass it to the + [DetectIntent][google.cloud.dialogflow.cx.v3.Sessions.DetectIntent] + method to determine user intent and respond. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SessionsTransport: + """Returns the transport used by the client instance. + + Returns: + SessionsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def session_path(project: str,location: str,agent: str,session: str,) -> str: + """Returns a fully-qualified session string.""" + return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format(project=project, location=location, agent=agent, session=session, ) + + @staticmethod + def parse_session_path(path: str) -> Dict[str,str]: + """Parses a session path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def session_entity_type_path(project: str,location: str,agent: str,session: str,entity_type: str,) -> str: + """Returns a fully-qualified session_entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, session=session, entity_type=entity_type, ) + + @staticmethod + def parse_session_entity_type_path(path: str) -> Dict[str,str]: + """Parses a session_entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SessionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sessions client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SessionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SessionsTransport): + # transport is a SessionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def detect_intent(self, + request: Union[session.DetectIntentRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.DetectIntentResponse: + r"""Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause session entity types to be updated, which + in turn might affect results of future queries. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DetectIntentRequest, dict]): + The request object. The request to detect user's intent. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.DetectIntentResponse: + The message returned from the + DetectIntent method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a session.DetectIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session.DetectIntentRequest): + request = session.DetectIntentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.detect_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("session", request.session), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def streaming_detect_intent(self, + requests: Iterator[session.StreamingDetectIntentRequest] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[session.StreamingDetectIntentResponse]: + r"""Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Args: + requests (Iterator[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentRequest]): + The request object iterator. The top-level message sent by the + client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent] + method. + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.output_audio_config]. + 2. If + [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio.config][google.cloud.dialogflow.cx.v3.AudioInput.config], + all subsequent messages must contain + [query_input.audio.audio][google.cloud.dialogflow.cx.v3.AudioInput.audio] + to continue with Speech recognition. + If you decide to rather detect an intent from text + input after you already started Speech recognition, + please send a message with + [query_input.text][google.cloud.dialogflow.cx.v3.QueryInput.text]. + However, note that: + + * Dialogflow will bill you for the audio duration so + far. * Dialogflow discards all Speech recognition + results in favor of the input text. + * Dialogflow will use the language code from the + first message. + After you sent all input, you must half-close or abort + the request stream. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.cloud.dialogflowcx_v3.types.StreamingDetectIntentResponse]: + The top-level message returned from the + StreamingDetectIntent method. + + Multiple response messages can be returned in order: + + 1. If the input was set to streaming audio, the first + one or more messages contain recognition_result. + Each recognition_result represents a more complete + transcript of what the user said. The last + recognition_result has is_final set to true. + 2. If enable_partial_response is true, the following + N messages (currently 1 <= N <= 4) contain + detect_intent_response. The first (N-1) + detect_intent_responses will have response_type + set to PARTIAL. The last detect_intent_response + has response_type set to FINAL. If response_type + is false, response stream only contains the final + detect_intent_response. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.streaming_detect_intent] + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def match_intent(self, + request: Union[session.MatchIntentRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.MatchIntentResponse: + r"""Returns preliminary intent match results, doesn't + change the session status. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.MatchIntentRequest, dict]): + The request object. Request of [MatchIntent][]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.MatchIntentResponse: + Response of [MatchIntent][]. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a session.MatchIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session.MatchIntentRequest): + request = session.MatchIntentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.match_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("session", request.session), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def fulfill_intent(self, + request: Union[session.FulfillIntentRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.FulfillIntentResponse: + r"""Fulfills a matched intent returned by + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent]. + Must be called after + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent], + with input from + [MatchIntentResponse][google.cloud.dialogflow.cx.v3.MatchIntentResponse]. + Otherwise, the behavior is undefined. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.FulfillIntentRequest, dict]): + The request object. Request of [FulfillIntent][] + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.FulfillIntentResponse: + Response of [FulfillIntent][] + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a session.FulfillIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session.FulfillIntentRequest): + request = session.FulfillIntentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fulfill_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("match_intent_request.session", request.match_intent_request.session), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py new file mode 100644 index 00000000..fde19f61 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SessionsTransport +from .grpc import SessionsGrpcTransport +from .grpc_asyncio import SessionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SessionsTransport]] +_transport_registry['grpc'] = SessionsGrpcTransport +_transport_registry['grpc_asyncio'] = SessionsGrpcAsyncIOTransport + +__all__ = ( + 'SessionsTransport', + 'SessionsGrpcTransport', + 'SessionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py new file mode 100644 index 00000000..a17ab798 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py @@ -0,0 +1,226 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import session + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class SessionsTransport(abc.ABC): + """Abstract transport class for Sessions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.detect_intent: gapic_v1.method.wrap_method( + self.detect_intent, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, + ), + default_timeout=220.0, + client_info=client_info, + ), + self.streaming_detect_intent: gapic_v1.method.wrap_method( + self.streaming_detect_intent, + default_timeout=220.0, + client_info=client_info, + ), + self.match_intent: gapic_v1.method.wrap_method( + self.match_intent, + default_timeout=None, + client_info=client_info, + ), + self.fulfill_intent: gapic_v1.method.wrap_method( + self.fulfill_intent, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def detect_intent(self) -> Callable[ + [session.DetectIntentRequest], + Union[ + session.DetectIntentResponse, + Awaitable[session.DetectIntentResponse] + ]]: + raise NotImplementedError() + + @property + def streaming_detect_intent(self) -> Callable[ + [session.StreamingDetectIntentRequest], + Union[ + session.StreamingDetectIntentResponse, + Awaitable[session.StreamingDetectIntentResponse] + ]]: + raise NotImplementedError() + + @property + def match_intent(self) -> Callable[ + [session.MatchIntentRequest], + Union[ + session.MatchIntentResponse, + Awaitable[session.MatchIntentResponse] + ]]: + raise NotImplementedError() + + @property + def fulfill_intent(self) -> Callable[ + [session.FulfillIntentRequest], + Union[ + session.FulfillIntentResponse, + Awaitable[session.FulfillIntentResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SessionsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py new file mode 100644 index 00000000..3e611b44 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py @@ -0,0 +1,356 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import session +from .base import SessionsTransport, DEFAULT_CLIENT_INFO + + +class SessionsGrpcTransport(SessionsTransport): + """gRPC backend transport for Sessions. + + A session represents an interaction with a user. You retrieve user + input and pass it to the + [DetectIntent][google.cloud.dialogflow.cx.v3.Sessions.DetectIntent] + method to determine user intent and respond. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def detect_intent(self) -> Callable[ + [session.DetectIntentRequest], + session.DetectIntentResponse]: + r"""Return a callable for the detect intent method over gRPC. + + Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause session entity types to be updated, which + in turn might affect results of future queries. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Returns: + Callable[[~.DetectIntentRequest], + ~.DetectIntentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'detect_intent' not in self._stubs: + self._stubs['detect_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Sessions/DetectIntent', + request_serializer=session.DetectIntentRequest.serialize, + response_deserializer=session.DetectIntentResponse.deserialize, + ) + return self._stubs['detect_intent'] + + @property + def streaming_detect_intent(self) -> Callable[ + [session.StreamingDetectIntentRequest], + session.StreamingDetectIntentResponse]: + r"""Return a callable for the streaming detect intent method over gRPC. + + Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Returns: + Callable[[~.StreamingDetectIntentRequest], + ~.StreamingDetectIntentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'streaming_detect_intent' not in self._stubs: + self._stubs['streaming_detect_intent'] = self.grpc_channel.stream_stream( + '/google.cloud.dialogflow.cx.v3.Sessions/StreamingDetectIntent', + request_serializer=session.StreamingDetectIntentRequest.serialize, + response_deserializer=session.StreamingDetectIntentResponse.deserialize, + ) + return self._stubs['streaming_detect_intent'] + + @property + def match_intent(self) -> Callable[ + [session.MatchIntentRequest], + session.MatchIntentResponse]: + r"""Return a callable for the match intent method over gRPC. + + Returns preliminary intent match results, doesn't + change the session status. + + Returns: + Callable[[~.MatchIntentRequest], + ~.MatchIntentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'match_intent' not in self._stubs: + self._stubs['match_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Sessions/MatchIntent', + request_serializer=session.MatchIntentRequest.serialize, + response_deserializer=session.MatchIntentResponse.deserialize, + ) + return self._stubs['match_intent'] + + @property + def fulfill_intent(self) -> Callable[ + [session.FulfillIntentRequest], + session.FulfillIntentResponse]: + r"""Return a callable for the fulfill intent method over gRPC. + + Fulfills a matched intent returned by + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent]. + Must be called after + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent], + with input from + [MatchIntentResponse][google.cloud.dialogflow.cx.v3.MatchIntentResponse]. + Otherwise, the behavior is undefined. + + Returns: + Callable[[~.FulfillIntentRequest], + ~.FulfillIntentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fulfill_intent' not in self._stubs: + self._stubs['fulfill_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Sessions/FulfillIntent', + request_serializer=session.FulfillIntentRequest.serialize, + response_deserializer=session.FulfillIntentResponse.deserialize, + ) + return self._stubs['fulfill_intent'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'SessionsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py new file mode 100644 index 00000000..bde59dc0 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py @@ -0,0 +1,361 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import session +from .base import SessionsTransport, DEFAULT_CLIENT_INFO +from .grpc import SessionsGrpcTransport + + +class SessionsGrpcAsyncIOTransport(SessionsTransport): + """gRPC AsyncIO backend transport for Sessions. + + A session represents an interaction with a user. You retrieve user + input and pass it to the + [DetectIntent][google.cloud.dialogflow.cx.v3.Sessions.DetectIntent] + method to determine user intent and respond. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def detect_intent(self) -> Callable[ + [session.DetectIntentRequest], + Awaitable[session.DetectIntentResponse]]: + r"""Return a callable for the detect intent method over gRPC. + + Processes a natural language query and returns structured, + actionable data as a result. This method is not idempotent, + because it may cause session entity types to be updated, which + in turn might affect results of future queries. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Returns: + Callable[[~.DetectIntentRequest], + Awaitable[~.DetectIntentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'detect_intent' not in self._stubs: + self._stubs['detect_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Sessions/DetectIntent', + request_serializer=session.DetectIntentRequest.serialize, + response_deserializer=session.DetectIntentResponse.deserialize, + ) + return self._stubs['detect_intent'] + + @property + def streaming_detect_intent(self) -> Callable[ + [session.StreamingDetectIntentRequest], + Awaitable[session.StreamingDetectIntentResponse]]: + r"""Return a callable for the streaming detect intent method over gRPC. + + Processes a natural language query in audio format in a + streaming fashion and returns structured, actionable data as a + result. This method is only available via the gRPC API (not + REST). + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + + Returns: + Callable[[~.StreamingDetectIntentRequest], + Awaitable[~.StreamingDetectIntentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'streaming_detect_intent' not in self._stubs: + self._stubs['streaming_detect_intent'] = self.grpc_channel.stream_stream( + '/google.cloud.dialogflow.cx.v3.Sessions/StreamingDetectIntent', + request_serializer=session.StreamingDetectIntentRequest.serialize, + response_deserializer=session.StreamingDetectIntentResponse.deserialize, + ) + return self._stubs['streaming_detect_intent'] + + @property + def match_intent(self) -> Callable[ + [session.MatchIntentRequest], + Awaitable[session.MatchIntentResponse]]: + r"""Return a callable for the match intent method over gRPC. + + Returns preliminary intent match results, doesn't + change the session status. + + Returns: + Callable[[~.MatchIntentRequest], + Awaitable[~.MatchIntentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'match_intent' not in self._stubs: + self._stubs['match_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Sessions/MatchIntent', + request_serializer=session.MatchIntentRequest.serialize, + response_deserializer=session.MatchIntentResponse.deserialize, + ) + return self._stubs['match_intent'] + + @property + def fulfill_intent(self) -> Callable[ + [session.FulfillIntentRequest], + Awaitable[session.FulfillIntentResponse]]: + r"""Return a callable for the fulfill intent method over gRPC. + + Fulfills a matched intent returned by + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent]. + Must be called after + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent], + with input from + [MatchIntentResponse][google.cloud.dialogflow.cx.v3.MatchIntentResponse]. + Otherwise, the behavior is undefined. + + Returns: + Callable[[~.FulfillIntentRequest], + Awaitable[~.FulfillIntentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fulfill_intent' not in self._stubs: + self._stubs['fulfill_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Sessions/FulfillIntent', + request_serializer=session.FulfillIntentRequest.serialize, + response_deserializer=session.FulfillIntentResponse.deserialize, + ) + return self._stubs['fulfill_intent'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'SessionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py new file mode 100644 index 00000000..938c210f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import TestCasesClient +from .async_client import TestCasesAsyncClient + +__all__ = ( + 'TestCasesClient', + 'TestCasesAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py new file mode 100644 index 00000000..4d834b9e --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py @@ -0,0 +1,1115 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflowcx_v3.services.test_cases import pagers +from google.cloud.dialogflowcx_v3.types import test_case +from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport +from .client import TestCasesClient + + +class TestCasesAsyncClient: + """Service for managing [Test + Cases][google.cloud.dialogflow.cx.v3.TestCase] and [Test Case + Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. + """ + + _client: TestCasesClient + + DEFAULT_ENDPOINT = TestCasesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TestCasesClient.DEFAULT_MTLS_ENDPOINT + + agent_path = staticmethod(TestCasesClient.agent_path) + parse_agent_path = staticmethod(TestCasesClient.parse_agent_path) + entity_type_path = staticmethod(TestCasesClient.entity_type_path) + parse_entity_type_path = staticmethod(TestCasesClient.parse_entity_type_path) + environment_path = staticmethod(TestCasesClient.environment_path) + parse_environment_path = staticmethod(TestCasesClient.parse_environment_path) + flow_path = staticmethod(TestCasesClient.flow_path) + parse_flow_path = staticmethod(TestCasesClient.parse_flow_path) + intent_path = staticmethod(TestCasesClient.intent_path) + parse_intent_path = staticmethod(TestCasesClient.parse_intent_path) + page_path = staticmethod(TestCasesClient.page_path) + parse_page_path = staticmethod(TestCasesClient.parse_page_path) + test_case_path = staticmethod(TestCasesClient.test_case_path) + parse_test_case_path = staticmethod(TestCasesClient.parse_test_case_path) + test_case_result_path = staticmethod(TestCasesClient.test_case_result_path) + parse_test_case_result_path = staticmethod(TestCasesClient.parse_test_case_result_path) + transition_route_group_path = staticmethod(TestCasesClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(TestCasesClient.parse_transition_route_group_path) + webhook_path = staticmethod(TestCasesClient.webhook_path) + parse_webhook_path = staticmethod(TestCasesClient.parse_webhook_path) + common_billing_account_path = staticmethod(TestCasesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TestCasesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TestCasesClient.common_folder_path) + parse_common_folder_path = staticmethod(TestCasesClient.parse_common_folder_path) + common_organization_path = staticmethod(TestCasesClient.common_organization_path) + parse_common_organization_path = staticmethod(TestCasesClient.parse_common_organization_path) + common_project_path = staticmethod(TestCasesClient.common_project_path) + parse_common_project_path = staticmethod(TestCasesClient.parse_common_project_path) + common_location_path = staticmethod(TestCasesClient.common_location_path) + parse_common_location_path = staticmethod(TestCasesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TestCasesAsyncClient: The constructed client. + """ + return TestCasesClient.from_service_account_info.__func__(TestCasesAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TestCasesAsyncClient: The constructed client. + """ + return TestCasesClient.from_service_account_file.__func__(TestCasesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> TestCasesTransport: + """Returns the transport used by the client instance. + + Returns: + TestCasesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(TestCasesClient).get_transport_class, type(TestCasesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, TestCasesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the test cases client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TestCasesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = TestCasesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_test_cases(self, + request: test_case.ListTestCasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTestCasesAsyncPager: + r"""Fetches a list of test cases for a given agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListTestCasesRequest`): + The request object. The request message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. + parent (:class:`str`): + Required. The agent to list all pages for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCasesAsyncPager: + The response message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = test_case.ListTestCasesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTestCasesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_delete_test_cases(self, + request: test_case.BatchDeleteTestCasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Batch deletes test cases. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.BatchDeleteTestCasesRequest`): + The request object. The request message for + [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases]. + parent (:class:`str`): + Required. The agent to delete test cases from. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = test_case.BatchDeleteTestCasesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_delete_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_test_case(self, + request: test_case.GetTestCaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCase: + r"""Gets a test case. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetTestCaseRequest`): + The request object. The request message for + [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3.TestCases.GetTestCase]. + name (:class:`str`): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = test_case.GetTestCaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_test_case, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_test_case(self, + request: gcdc_test_case.CreateTestCaseRequest = None, + *, + parent: str = None, + test_case: gcdc_test_case.TestCase = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_test_case.TestCase: + r"""Creates a test case for the given agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateTestCaseRequest`): + The request object. The request message for + [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase]. + parent (:class:`str`): + Required. The agent to create the test case for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + test_case (:class:`google.cloud.dialogflowcx_v3.types.TestCase`): + Required. The test case to create. + This corresponds to the ``test_case`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, test_case]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_test_case.CreateTestCaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if test_case is not None: + request.test_case = test_case + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_test_case, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_test_case(self, + request: gcdc_test_case.UpdateTestCaseRequest = None, + *, + test_case: gcdc_test_case.TestCase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_test_case.TestCase: + r"""Updates the specified test case. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateTestCaseRequest`): + The request object. The request message for + [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase]. + test_case (:class:`google.cloud.dialogflowcx_v3.types.TestCase`): + Required. The test case to update. + This corresponds to the ``test_case`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to specify which fields should be + updated. The + [``creationTime``][google.cloud.dialogflow.cx.v3.TestCase.creation_time] + and + [``lastTestResult``][google.cloud.dialogflow.cx.v3.TestCase.last_test_result] + cannot be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([test_case, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_test_case.UpdateTestCaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if test_case is not None: + request.test_case = test_case + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_test_case, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("test_case.name", request.test_case.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_test_case(self, + request: test_case.RunTestCaseRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off a test case run. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [RunTestCaseMetadata][google.cloud.dialogflow.cx.v3.RunTestCaseMetadata] + - ``response``: + [RunTestCaseResponse][google.cloud.dialogflow.cx.v3.RunTestCaseResponse] + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.RunTestCaseRequest`): + The request object. The request message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.RunTestCaseResponse` + The response message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. + + """ + # Create or coerce a protobuf request object. + request = test_case.RunTestCaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.run_test_case, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + test_case.RunTestCaseResponse, + metadata_type=test_case.RunTestCaseMetadata, + ) + + # Done; return the response. + return response + + async def batch_run_test_cases(self, + request: test_case.BatchRunTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off a batch run of test cases. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [BatchRunTestCasesMetadata][google.cloud.dialogflow.cx.v3.BatchRunTestCasesMetadata] + - ``response``: + [BatchRunTestCasesResponse][google.cloud.dialogflow.cx.v3.BatchRunTestCasesResponse] + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest`): + The request object. The request message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.BatchRunTestCasesResponse` + The response message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. + + """ + # Create or coerce a protobuf request object. + request = test_case.BatchRunTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_run_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + test_case.BatchRunTestCasesResponse, + metadata_type=test_case.BatchRunTestCasesMetadata, + ) + + # Done; return the response. + return response + + async def calculate_coverage(self, + request: test_case.CalculateCoverageRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.CalculateCoverageResponse: + r"""Calculates the test coverage for an agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest`): + The request object. The request message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.CalculateCoverageResponse: + The response message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. + + """ + # Create or coerce a protobuf request object. + request = test_case.CalculateCoverageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.calculate_coverage, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent", request.agent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_test_cases(self, + request: test_case.ImportTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports the test cases from a Cloud Storage bucket or a local + file. It always creates new test cases and won't overwite any + existing ones. The provided ID in the imported test case is + neglected. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ImportTestCasesMetadata][google.cloud.dialogflow.cx.v3.ImportTestCasesMetadata] + - ``response``: + [ImportTestCasesResponse][google.cloud.dialogflow.cx.v3.ImportTestCasesResponse] + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest`): + The request object. The request message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ImportTestCasesResponse` + The response message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. + + """ + # Create or coerce a protobuf request object. + request = test_case.ImportTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + test_case.ImportTestCasesResponse, + metadata_type=test_case.ImportTestCasesMetadata, + ) + + # Done; return the response. + return response + + async def export_test_cases(self, + request: test_case.ExportTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the test cases under the agent to a Cloud Storage bucket + or a local file. Filter can be applied to export a subset of + test cases. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ExportTestCasesMetadata][google.cloud.dialogflow.cx.v3.ExportTestCasesMetadata] + - ``response``: + [ExportTestCasesResponse][google.cloud.dialogflow.cx.v3.ExportTestCasesResponse] + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest`): + The request object. The request message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportTestCasesResponse` + The response message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. + + """ + # Create or coerce a protobuf request object. + request = test_case.ExportTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + test_case.ExportTestCasesResponse, + metadata_type=test_case.ExportTestCasesMetadata, + ) + + # Done; return the response. + return response + + async def list_test_case_results(self, + request: test_case.ListTestCaseResultsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTestCaseResultsAsyncPager: + r"""Fetches a list of results for a given test case. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest`): + The request object. The request message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. + parent (:class:`str`): + Required. The test case to list results for. Format: + ``projects//locations//agents// testCases/``. + Specify a ``-`` as a wildcard for TestCase ID to list + results across multiple test cases. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCaseResultsAsyncPager: + The response message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = test_case.ListTestCaseResultsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_test_case_results, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTestCaseResultsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_test_case_result(self, + request: test_case.GetTestCaseResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCaseResult: + r"""Gets a test case result. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest`): + The request object. The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult]. + name (:class:`str`): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCaseResult: + Represents a result from running a + test case in an agent environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = test_case.GetTestCaseResultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_test_case_result, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TestCasesAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/client.py new file mode 100644 index 00000000..6c644d2a --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/client.py @@ -0,0 +1,1398 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflowcx_v3.services.test_cases import pagers +from google.cloud.dialogflowcx_v3.types import test_case +from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TestCasesGrpcTransport +from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport + + +class TestCasesClientMeta(type): + """Metaclass for the TestCases client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[TestCasesTransport]] + _transport_registry["grpc"] = TestCasesGrpcTransport + _transport_registry["grpc_asyncio"] = TestCasesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[TestCasesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class TestCasesClient(metaclass=TestCasesClientMeta): + """Service for managing [Test + Cases][google.cloud.dialogflow.cx.v3.TestCase] and [Test Case + Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TestCasesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TestCasesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> TestCasesTransport: + """Returns the transport used by the client instance. + + Returns: + TestCasesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def agent_path(project: str,location: str,agent: str,) -> str: + """Returns a fully-qualified agent string.""" + return "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str,str]: + """Parses a agent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def environment_path(project: str,location: str,agent: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def test_case_path(project: str,location: str,agent: str,test_case: str,) -> str: + """Returns a fully-qualified test_case string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format(project=project, location=location, agent=agent, test_case=test_case, ) + + @staticmethod + def parse_test_case_path(path: str) -> Dict[str,str]: + """Parses a test_case path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def test_case_result_path(project: str,location: str,agent: str,test_case: str,result: str,) -> str: + """Returns a fully-qualified test_case_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) + + @staticmethod + def parse_test_case_result_path(path: str) -> Dict[str,str]: + """Parses a test_case_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, TestCasesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the test cases client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, TestCasesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, TestCasesTransport): + # transport is a TestCasesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_test_cases(self, + request: Union[test_case.ListTestCasesRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTestCasesPager: + r"""Fetches a list of test cases for a given agent. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListTestCasesRequest, dict]): + The request object. The request message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. + parent (str): + Required. The agent to list all pages for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCasesPager: + The response message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a test_case.ListTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.ListTestCasesRequest): + request = test_case.ListTestCasesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTestCasesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_delete_test_cases(self, + request: Union[test_case.BatchDeleteTestCasesRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Batch deletes test cases. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.BatchDeleteTestCasesRequest, dict]): + The request object. The request message for + [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases]. + parent (str): + Required. The agent to delete test cases from. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a test_case.BatchDeleteTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.BatchDeleteTestCasesRequest): + request = test_case.BatchDeleteTestCasesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_test_case(self, + request: Union[test_case.GetTestCaseRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCase: + r"""Gets a test case. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetTestCaseRequest, dict]): + The request object. The request message for + [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3.TestCases.GetTestCase]. + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a test_case.GetTestCaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.GetTestCaseRequest): + request = test_case.GetTestCaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_test_case] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_test_case(self, + request: Union[gcdc_test_case.CreateTestCaseRequest, dict] = None, + *, + parent: str = None, + test_case: gcdc_test_case.TestCase = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_test_case.TestCase: + r"""Creates a test case for the given agent. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateTestCaseRequest, dict]): + The request object. The request message for + [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase]. + parent (str): + Required. The agent to create the test case for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + test_case (google.cloud.dialogflowcx_v3.types.TestCase): + Required. The test case to create. + This corresponds to the ``test_case`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, test_case]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_test_case.CreateTestCaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_test_case.CreateTestCaseRequest): + request = gcdc_test_case.CreateTestCaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if test_case is not None: + request.test_case = test_case + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_test_case] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_test_case(self, + request: Union[gcdc_test_case.UpdateTestCaseRequest, dict] = None, + *, + test_case: gcdc_test_case.TestCase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_test_case.TestCase: + r"""Updates the specified test case. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateTestCaseRequest, dict]): + The request object. The request message for + [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase]. + test_case (google.cloud.dialogflowcx_v3.types.TestCase): + Required. The test case to update. + This corresponds to the ``test_case`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to specify which fields should be + updated. The + [``creationTime``][google.cloud.dialogflow.cx.v3.TestCase.creation_time] + and + [``lastTestResult``][google.cloud.dialogflow.cx.v3.TestCase.last_test_result] + cannot be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([test_case, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_test_case.UpdateTestCaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_test_case.UpdateTestCaseRequest): + request = gcdc_test_case.UpdateTestCaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if test_case is not None: + request.test_case = test_case + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_test_case] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("test_case.name", request.test_case.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_test_case(self, + request: Union[test_case.RunTestCaseRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Kicks off a test case run. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [RunTestCaseMetadata][google.cloud.dialogflow.cx.v3.RunTestCaseMetadata] + - ``response``: + [RunTestCaseResponse][google.cloud.dialogflow.cx.v3.RunTestCaseResponse] + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.RunTestCaseRequest, dict]): + The request object. The request message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.RunTestCaseResponse` + The response message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.RunTestCaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.RunTestCaseRequest): + request = test_case.RunTestCaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_test_case] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + test_case.RunTestCaseResponse, + metadata_type=test_case.RunTestCaseMetadata, + ) + + # Done; return the response. + return response + + def batch_run_test_cases(self, + request: Union[test_case.BatchRunTestCasesRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Kicks off a batch run of test cases. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [BatchRunTestCasesMetadata][google.cloud.dialogflow.cx.v3.BatchRunTestCasesMetadata] + - ``response``: + [BatchRunTestCasesResponse][google.cloud.dialogflow.cx.v3.BatchRunTestCasesResponse] + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest, dict]): + The request object. The request message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.BatchRunTestCasesResponse` + The response message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.BatchRunTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.BatchRunTestCasesRequest): + request = test_case.BatchRunTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_run_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + test_case.BatchRunTestCasesResponse, + metadata_type=test_case.BatchRunTestCasesMetadata, + ) + + # Done; return the response. + return response + + def calculate_coverage(self, + request: Union[test_case.CalculateCoverageRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.CalculateCoverageResponse: + r"""Calculates the test coverage for an agent. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest, dict]): + The request object. The request message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.CalculateCoverageResponse: + The response message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.CalculateCoverageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.CalculateCoverageRequest): + request = test_case.CalculateCoverageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.calculate_coverage] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent", request.agent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_test_cases(self, + request: Union[test_case.ImportTestCasesRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports the test cases from a Cloud Storage bucket or a local + file. It always creates new test cases and won't overwite any + existing ones. The provided ID in the imported test case is + neglected. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ImportTestCasesMetadata][google.cloud.dialogflow.cx.v3.ImportTestCasesMetadata] + - ``response``: + [ImportTestCasesResponse][google.cloud.dialogflow.cx.v3.ImportTestCasesResponse] + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest, dict]): + The request object. The request message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ImportTestCasesResponse` + The response message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.ImportTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.ImportTestCasesRequest): + request = test_case.ImportTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + test_case.ImportTestCasesResponse, + metadata_type=test_case.ImportTestCasesMetadata, + ) + + # Done; return the response. + return response + + def export_test_cases(self, + request: Union[test_case.ExportTestCasesRequest, dict] = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the test cases under the agent to a Cloud Storage bucket + or a local file. Filter can be applied to export a subset of + test cases. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ExportTestCasesMetadata][google.cloud.dialogflow.cx.v3.ExportTestCasesMetadata] + - ``response``: + [ExportTestCasesResponse][google.cloud.dialogflow.cx.v3.ExportTestCasesResponse] + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest, dict]): + The request object. The request message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportTestCasesResponse` + The response message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.ExportTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.ExportTestCasesRequest): + request = test_case.ExportTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + test_case.ExportTestCasesResponse, + metadata_type=test_case.ExportTestCasesMetadata, + ) + + # Done; return the response. + return response + + def list_test_case_results(self, + request: Union[test_case.ListTestCaseResultsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTestCaseResultsPager: + r"""Fetches a list of results for a given test case. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest, dict]): + The request object. The request message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. + parent (str): + Required. The test case to list results for. Format: + ``projects//locations//agents// testCases/``. + Specify a ``-`` as a wildcard for TestCase ID to list + results across multiple test cases. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCaseResultsPager: + The response message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a test_case.ListTestCaseResultsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.ListTestCaseResultsRequest): + request = test_case.ListTestCaseResultsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_test_case_results] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTestCaseResultsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_test_case_result(self, + request: Union[test_case.GetTestCaseResultRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCaseResult: + r"""Gets a test case result. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest, dict]): + The request object. The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult]. + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCaseResult: + Represents a result from running a + test case in an agent environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a test_case.GetTestCaseResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.GetTestCaseResultRequest): + request = test_case.GetTestCaseResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_test_case_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TestCasesClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py new file mode 100644 index 00000000..53769875 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import test_case + + +class ListTestCasesPager: + """A pager for iterating through ``list_test_cases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListTestCasesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``test_cases`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTestCases`` requests and continue to iterate + through the ``test_cases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTestCasesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., test_case.ListTestCasesResponse], + request: test_case.ListTestCasesRequest, + response: test_case.ListTestCasesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListTestCasesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListTestCasesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = test_case.ListTestCasesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[test_case.ListTestCasesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[test_case.TestCase]: + for page in self.pages: + yield from page.test_cases + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTestCasesAsyncPager: + """A pager for iterating through ``list_test_cases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListTestCasesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``test_cases`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTestCases`` requests and continue to iterate + through the ``test_cases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTestCasesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[test_case.ListTestCasesResponse]], + request: test_case.ListTestCasesRequest, + response: test_case.ListTestCasesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListTestCasesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListTestCasesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = test_case.ListTestCasesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[test_case.ListTestCasesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[test_case.TestCase]: + async def async_generator(): + async for page in self.pages: + for response in page.test_cases: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTestCaseResultsPager: + """A pager for iterating through ``list_test_case_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``test_case_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTestCaseResults`` requests and continue to iterate + through the ``test_case_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., test_case.ListTestCaseResultsResponse], + request: test_case.ListTestCaseResultsRequest, + response: test_case.ListTestCaseResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = test_case.ListTestCaseResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[test_case.ListTestCaseResultsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[test_case.TestCaseResult]: + for page in self.pages: + yield from page.test_case_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTestCaseResultsAsyncPager: + """A pager for iterating through ``list_test_case_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``test_case_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTestCaseResults`` requests and continue to iterate + through the ``test_case_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[test_case.ListTestCaseResultsResponse]], + request: test_case.ListTestCaseResultsRequest, + response: test_case.ListTestCaseResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = test_case.ListTestCaseResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[test_case.ListTestCaseResultsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[test_case.TestCaseResult]: + async def async_generator(): + async for page in self.pages: + for response in page.test_case_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py new file mode 100644 index 00000000..52d2730d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import TestCasesTransport +from .grpc import TestCasesGrpcTransport +from .grpc_asyncio import TestCasesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TestCasesTransport]] +_transport_registry['grpc'] = TestCasesGrpcTransport +_transport_registry['grpc_asyncio'] = TestCasesGrpcAsyncIOTransport + +__all__ = ( + 'TestCasesTransport', + 'TestCasesGrpcTransport', + 'TestCasesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py new file mode 100644 index 00000000..165a8776 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py @@ -0,0 +1,341 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import test_case +from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class TestCasesTransport(abc.ABC): + """Abstract transport class for TestCases.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_test_cases: gapic_v1.method.wrap_method( + self.list_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_test_cases: gapic_v1.method.wrap_method( + self.batch_delete_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.get_test_case: gapic_v1.method.wrap_method( + self.get_test_case, + default_timeout=None, + client_info=client_info, + ), + self.create_test_case: gapic_v1.method.wrap_method( + self.create_test_case, + default_timeout=None, + client_info=client_info, + ), + self.update_test_case: gapic_v1.method.wrap_method( + self.update_test_case, + default_timeout=None, + client_info=client_info, + ), + self.run_test_case: gapic_v1.method.wrap_method( + self.run_test_case, + default_timeout=None, + client_info=client_info, + ), + self.batch_run_test_cases: gapic_v1.method.wrap_method( + self.batch_run_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.calculate_coverage: gapic_v1.method.wrap_method( + self.calculate_coverage, + default_timeout=None, + client_info=client_info, + ), + self.import_test_cases: gapic_v1.method.wrap_method( + self.import_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.export_test_cases: gapic_v1.method.wrap_method( + self.export_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.list_test_case_results: gapic_v1.method.wrap_method( + self.list_test_case_results, + default_timeout=None, + client_info=client_info, + ), + self.get_test_case_result: gapic_v1.method.wrap_method( + self.get_test_case_result, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_test_cases(self) -> Callable[ + [test_case.ListTestCasesRequest], + Union[ + test_case.ListTestCasesResponse, + Awaitable[test_case.ListTestCasesResponse] + ]]: + raise NotImplementedError() + + @property + def batch_delete_test_cases(self) -> Callable[ + [test_case.BatchDeleteTestCasesRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_test_case(self) -> Callable[ + [test_case.GetTestCaseRequest], + Union[ + test_case.TestCase, + Awaitable[test_case.TestCase] + ]]: + raise NotImplementedError() + + @property + def create_test_case(self) -> Callable[ + [gcdc_test_case.CreateTestCaseRequest], + Union[ + gcdc_test_case.TestCase, + Awaitable[gcdc_test_case.TestCase] + ]]: + raise NotImplementedError() + + @property + def update_test_case(self) -> Callable[ + [gcdc_test_case.UpdateTestCaseRequest], + Union[ + gcdc_test_case.TestCase, + Awaitable[gcdc_test_case.TestCase] + ]]: + raise NotImplementedError() + + @property + def run_test_case(self) -> Callable[ + [test_case.RunTestCaseRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_run_test_cases(self) -> Callable[ + [test_case.BatchRunTestCasesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def calculate_coverage(self) -> Callable[ + [test_case.CalculateCoverageRequest], + Union[ + test_case.CalculateCoverageResponse, + Awaitable[test_case.CalculateCoverageResponse] + ]]: + raise NotImplementedError() + + @property + def import_test_cases(self) -> Callable[ + [test_case.ImportTestCasesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_test_cases(self) -> Callable[ + [test_case.ExportTestCasesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_test_case_results(self) -> Callable[ + [test_case.ListTestCaseResultsRequest], + Union[ + test_case.ListTestCaseResultsResponse, + Awaitable[test_case.ListTestCaseResultsResponse] + ]]: + raise NotImplementedError() + + @property + def get_test_case_result(self) -> Callable[ + [test_case.GetTestCaseResultRequest], + Union[ + test_case.TestCaseResult, + Awaitable[test_case.TestCaseResult] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'TestCasesTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py new file mode 100644 index 00000000..bfa31b2b --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py @@ -0,0 +1,608 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import test_case +from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import TestCasesTransport, DEFAULT_CLIENT_INFO + + +class TestCasesGrpcTransport(TestCasesTransport): + """gRPC backend transport for TestCases. + + Service for managing [Test + Cases][google.cloud.dialogflow.cx.v3.TestCase] and [Test Case + Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_test_cases(self) -> Callable[ + [test_case.ListTestCasesRequest], + test_case.ListTestCasesResponse]: + r"""Return a callable for the list test cases method over gRPC. + + Fetches a list of test cases for a given agent. + + Returns: + Callable[[~.ListTestCasesRequest], + ~.ListTestCasesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_test_cases' not in self._stubs: + self._stubs['list_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ListTestCases', + request_serializer=test_case.ListTestCasesRequest.serialize, + response_deserializer=test_case.ListTestCasesResponse.deserialize, + ) + return self._stubs['list_test_cases'] + + @property + def batch_delete_test_cases(self) -> Callable[ + [test_case.BatchDeleteTestCasesRequest], + empty_pb2.Empty]: + r"""Return a callable for the batch delete test cases method over gRPC. + + Batch deletes test cases. + + Returns: + Callable[[~.BatchDeleteTestCasesRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_test_cases' not in self._stubs: + self._stubs['batch_delete_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/BatchDeleteTestCases', + request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['batch_delete_test_cases'] + + @property + def get_test_case(self) -> Callable[ + [test_case.GetTestCaseRequest], + test_case.TestCase]: + r"""Return a callable for the get test case method over gRPC. + + Gets a test case. + + Returns: + Callable[[~.GetTestCaseRequest], + ~.TestCase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_test_case' not in self._stubs: + self._stubs['get_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/GetTestCase', + request_serializer=test_case.GetTestCaseRequest.serialize, + response_deserializer=test_case.TestCase.deserialize, + ) + return self._stubs['get_test_case'] + + @property + def create_test_case(self) -> Callable[ + [gcdc_test_case.CreateTestCaseRequest], + gcdc_test_case.TestCase]: + r"""Return a callable for the create test case method over gRPC. + + Creates a test case for the given agent. + + Returns: + Callable[[~.CreateTestCaseRequest], + ~.TestCase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_test_case' not in self._stubs: + self._stubs['create_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/CreateTestCase', + request_serializer=gcdc_test_case.CreateTestCaseRequest.serialize, + response_deserializer=gcdc_test_case.TestCase.deserialize, + ) + return self._stubs['create_test_case'] + + @property + def update_test_case(self) -> Callable[ + [gcdc_test_case.UpdateTestCaseRequest], + gcdc_test_case.TestCase]: + r"""Return a callable for the update test case method over gRPC. + + Updates the specified test case. + + Returns: + Callable[[~.UpdateTestCaseRequest], + ~.TestCase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_test_case' not in self._stubs: + self._stubs['update_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/UpdateTestCase', + request_serializer=gcdc_test_case.UpdateTestCaseRequest.serialize, + response_deserializer=gcdc_test_case.TestCase.deserialize, + ) + return self._stubs['update_test_case'] + + @property + def run_test_case(self) -> Callable[ + [test_case.RunTestCaseRequest], + operations_pb2.Operation]: + r"""Return a callable for the run test case method over gRPC. + + Kicks off a test case run. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [RunTestCaseMetadata][google.cloud.dialogflow.cx.v3.RunTestCaseMetadata] + - ``response``: + [RunTestCaseResponse][google.cloud.dialogflow.cx.v3.RunTestCaseResponse] + + Returns: + Callable[[~.RunTestCaseRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_test_case' not in self._stubs: + self._stubs['run_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/RunTestCase', + request_serializer=test_case.RunTestCaseRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_test_case'] + + @property + def batch_run_test_cases(self) -> Callable[ + [test_case.BatchRunTestCasesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch run test cases method over gRPC. + + Kicks off a batch run of test cases. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [BatchRunTestCasesMetadata][google.cloud.dialogflow.cx.v3.BatchRunTestCasesMetadata] + - ``response``: + [BatchRunTestCasesResponse][google.cloud.dialogflow.cx.v3.BatchRunTestCasesResponse] + + Returns: + Callable[[~.BatchRunTestCasesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_run_test_cases' not in self._stubs: + self._stubs['batch_run_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/BatchRunTestCases', + request_serializer=test_case.BatchRunTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_run_test_cases'] + + @property + def calculate_coverage(self) -> Callable[ + [test_case.CalculateCoverageRequest], + test_case.CalculateCoverageResponse]: + r"""Return a callable for the calculate coverage method over gRPC. + + Calculates the test coverage for an agent. + + Returns: + Callable[[~.CalculateCoverageRequest], + ~.CalculateCoverageResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'calculate_coverage' not in self._stubs: + self._stubs['calculate_coverage'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/CalculateCoverage', + request_serializer=test_case.CalculateCoverageRequest.serialize, + response_deserializer=test_case.CalculateCoverageResponse.deserialize, + ) + return self._stubs['calculate_coverage'] + + @property + def import_test_cases(self) -> Callable[ + [test_case.ImportTestCasesRequest], + operations_pb2.Operation]: + r"""Return a callable for the import test cases method over gRPC. + + Imports the test cases from a Cloud Storage bucket or a local + file. It always creates new test cases and won't overwite any + existing ones. The provided ID in the imported test case is + neglected. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ImportTestCasesMetadata][google.cloud.dialogflow.cx.v3.ImportTestCasesMetadata] + - ``response``: + [ImportTestCasesResponse][google.cloud.dialogflow.cx.v3.ImportTestCasesResponse] + + Returns: + Callable[[~.ImportTestCasesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_test_cases' not in self._stubs: + self._stubs['import_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ImportTestCases', + request_serializer=test_case.ImportTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_test_cases'] + + @property + def export_test_cases(self) -> Callable[ + [test_case.ExportTestCasesRequest], + operations_pb2.Operation]: + r"""Return a callable for the export test cases method over gRPC. + + Exports the test cases under the agent to a Cloud Storage bucket + or a local file. Filter can be applied to export a subset of + test cases. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ExportTestCasesMetadata][google.cloud.dialogflow.cx.v3.ExportTestCasesMetadata] + - ``response``: + [ExportTestCasesResponse][google.cloud.dialogflow.cx.v3.ExportTestCasesResponse] + + Returns: + Callable[[~.ExportTestCasesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_test_cases' not in self._stubs: + self._stubs['export_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ExportTestCases', + request_serializer=test_case.ExportTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_test_cases'] + + @property + def list_test_case_results(self) -> Callable[ + [test_case.ListTestCaseResultsRequest], + test_case.ListTestCaseResultsResponse]: + r"""Return a callable for the list test case results method over gRPC. + + Fetches a list of results for a given test case. + + Returns: + Callable[[~.ListTestCaseResultsRequest], + ~.ListTestCaseResultsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_test_case_results' not in self._stubs: + self._stubs['list_test_case_results'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ListTestCaseResults', + request_serializer=test_case.ListTestCaseResultsRequest.serialize, + response_deserializer=test_case.ListTestCaseResultsResponse.deserialize, + ) + return self._stubs['list_test_case_results'] + + @property + def get_test_case_result(self) -> Callable[ + [test_case.GetTestCaseResultRequest], + test_case.TestCaseResult]: + r"""Return a callable for the get test case result method over gRPC. + + Gets a test case result. + + Returns: + Callable[[~.GetTestCaseResultRequest], + ~.TestCaseResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_test_case_result' not in self._stubs: + self._stubs['get_test_case_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/GetTestCaseResult', + request_serializer=test_case.GetTestCaseResultRequest.serialize, + response_deserializer=test_case.TestCaseResult.deserialize, + ) + return self._stubs['get_test_case_result'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'TestCasesGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py new file mode 100644 index 00000000..57da5699 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py @@ -0,0 +1,613 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import test_case +from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import TestCasesTransport, DEFAULT_CLIENT_INFO +from .grpc import TestCasesGrpcTransport + + +class TestCasesGrpcAsyncIOTransport(TestCasesTransport): + """gRPC AsyncIO backend transport for TestCases. + + Service for managing [Test + Cases][google.cloud.dialogflow.cx.v3.TestCase] and [Test Case + Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_test_cases(self) -> Callable[ + [test_case.ListTestCasesRequest], + Awaitable[test_case.ListTestCasesResponse]]: + r"""Return a callable for the list test cases method over gRPC. + + Fetches a list of test cases for a given agent. + + Returns: + Callable[[~.ListTestCasesRequest], + Awaitable[~.ListTestCasesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_test_cases' not in self._stubs: + self._stubs['list_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ListTestCases', + request_serializer=test_case.ListTestCasesRequest.serialize, + response_deserializer=test_case.ListTestCasesResponse.deserialize, + ) + return self._stubs['list_test_cases'] + + @property + def batch_delete_test_cases(self) -> Callable[ + [test_case.BatchDeleteTestCasesRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the batch delete test cases method over gRPC. + + Batch deletes test cases. + + Returns: + Callable[[~.BatchDeleteTestCasesRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_delete_test_cases' not in self._stubs: + self._stubs['batch_delete_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/BatchDeleteTestCases', + request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['batch_delete_test_cases'] + + @property + def get_test_case(self) -> Callable[ + [test_case.GetTestCaseRequest], + Awaitable[test_case.TestCase]]: + r"""Return a callable for the get test case method over gRPC. + + Gets a test case. + + Returns: + Callable[[~.GetTestCaseRequest], + Awaitable[~.TestCase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_test_case' not in self._stubs: + self._stubs['get_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/GetTestCase', + request_serializer=test_case.GetTestCaseRequest.serialize, + response_deserializer=test_case.TestCase.deserialize, + ) + return self._stubs['get_test_case'] + + @property + def create_test_case(self) -> Callable[ + [gcdc_test_case.CreateTestCaseRequest], + Awaitable[gcdc_test_case.TestCase]]: + r"""Return a callable for the create test case method over gRPC. + + Creates a test case for the given agent. + + Returns: + Callable[[~.CreateTestCaseRequest], + Awaitable[~.TestCase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_test_case' not in self._stubs: + self._stubs['create_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/CreateTestCase', + request_serializer=gcdc_test_case.CreateTestCaseRequest.serialize, + response_deserializer=gcdc_test_case.TestCase.deserialize, + ) + return self._stubs['create_test_case'] + + @property + def update_test_case(self) -> Callable[ + [gcdc_test_case.UpdateTestCaseRequest], + Awaitable[gcdc_test_case.TestCase]]: + r"""Return a callable for the update test case method over gRPC. + + Updates the specified test case. + + Returns: + Callable[[~.UpdateTestCaseRequest], + Awaitable[~.TestCase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_test_case' not in self._stubs: + self._stubs['update_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/UpdateTestCase', + request_serializer=gcdc_test_case.UpdateTestCaseRequest.serialize, + response_deserializer=gcdc_test_case.TestCase.deserialize, + ) + return self._stubs['update_test_case'] + + @property + def run_test_case(self) -> Callable[ + [test_case.RunTestCaseRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run test case method over gRPC. + + Kicks off a test case run. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [RunTestCaseMetadata][google.cloud.dialogflow.cx.v3.RunTestCaseMetadata] + - ``response``: + [RunTestCaseResponse][google.cloud.dialogflow.cx.v3.RunTestCaseResponse] + + Returns: + Callable[[~.RunTestCaseRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_test_case' not in self._stubs: + self._stubs['run_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/RunTestCase', + request_serializer=test_case.RunTestCaseRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_test_case'] + + @property + def batch_run_test_cases(self) -> Callable[ + [test_case.BatchRunTestCasesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch run test cases method over gRPC. + + Kicks off a batch run of test cases. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [BatchRunTestCasesMetadata][google.cloud.dialogflow.cx.v3.BatchRunTestCasesMetadata] + - ``response``: + [BatchRunTestCasesResponse][google.cloud.dialogflow.cx.v3.BatchRunTestCasesResponse] + + Returns: + Callable[[~.BatchRunTestCasesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_run_test_cases' not in self._stubs: + self._stubs['batch_run_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/BatchRunTestCases', + request_serializer=test_case.BatchRunTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_run_test_cases'] + + @property + def calculate_coverage(self) -> Callable[ + [test_case.CalculateCoverageRequest], + Awaitable[test_case.CalculateCoverageResponse]]: + r"""Return a callable for the calculate coverage method over gRPC. + + Calculates the test coverage for an agent. + + Returns: + Callable[[~.CalculateCoverageRequest], + Awaitable[~.CalculateCoverageResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'calculate_coverage' not in self._stubs: + self._stubs['calculate_coverage'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/CalculateCoverage', + request_serializer=test_case.CalculateCoverageRequest.serialize, + response_deserializer=test_case.CalculateCoverageResponse.deserialize, + ) + return self._stubs['calculate_coverage'] + + @property + def import_test_cases(self) -> Callable[ + [test_case.ImportTestCasesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import test cases method over gRPC. + + Imports the test cases from a Cloud Storage bucket or a local + file. It always creates new test cases and won't overwite any + existing ones. The provided ID in the imported test case is + neglected. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ImportTestCasesMetadata][google.cloud.dialogflow.cx.v3.ImportTestCasesMetadata] + - ``response``: + [ImportTestCasesResponse][google.cloud.dialogflow.cx.v3.ImportTestCasesResponse] + + Returns: + Callable[[~.ImportTestCasesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_test_cases' not in self._stubs: + self._stubs['import_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ImportTestCases', + request_serializer=test_case.ImportTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_test_cases'] + + @property + def export_test_cases(self) -> Callable[ + [test_case.ExportTestCasesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export test cases method over gRPC. + + Exports the test cases under the agent to a Cloud Storage bucket + or a local file. Filter can be applied to export a subset of + test cases. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [ExportTestCasesMetadata][google.cloud.dialogflow.cx.v3.ExportTestCasesMetadata] + - ``response``: + [ExportTestCasesResponse][google.cloud.dialogflow.cx.v3.ExportTestCasesResponse] + + Returns: + Callable[[~.ExportTestCasesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_test_cases' not in self._stubs: + self._stubs['export_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ExportTestCases', + request_serializer=test_case.ExportTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_test_cases'] + + @property + def list_test_case_results(self) -> Callable[ + [test_case.ListTestCaseResultsRequest], + Awaitable[test_case.ListTestCaseResultsResponse]]: + r"""Return a callable for the list test case results method over gRPC. + + Fetches a list of results for a given test case. + + Returns: + Callable[[~.ListTestCaseResultsRequest], + Awaitable[~.ListTestCaseResultsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_test_case_results' not in self._stubs: + self._stubs['list_test_case_results'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ListTestCaseResults', + request_serializer=test_case.ListTestCaseResultsRequest.serialize, + response_deserializer=test_case.ListTestCaseResultsResponse.deserialize, + ) + return self._stubs['list_test_case_results'] + + @property + def get_test_case_result(self) -> Callable[ + [test_case.GetTestCaseResultRequest], + Awaitable[test_case.TestCaseResult]]: + r"""Return a callable for the get test case result method over gRPC. + + Gets a test case result. + + Returns: + Callable[[~.GetTestCaseResultRequest], + Awaitable[~.TestCaseResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_test_case_result' not in self._stubs: + self._stubs['get_test_case_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/GetTestCaseResult', + request_serializer=test_case.GetTestCaseResultRequest.serialize, + response_deserializer=test_case.TestCaseResult.deserialize, + ) + return self._stubs['get_test_case_result'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'TestCasesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py new file mode 100644 index 00000000..8e43702f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import TransitionRouteGroupsClient +from .async_client import TransitionRouteGroupsAsyncClient + +__all__ = ( + 'TransitionRouteGroupsClient', + 'TransitionRouteGroupsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py new file mode 100644 index 00000000..b8f13cca --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py @@ -0,0 +1,607 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.transition_route_groups import pagers +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import transition_route_group +from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport +from .client import TransitionRouteGroupsClient + + +class TransitionRouteGroupsAsyncClient: + """Service for managing + [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + """ + + _client: TransitionRouteGroupsClient + + DEFAULT_ENDPOINT = TransitionRouteGroupsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TransitionRouteGroupsClient.DEFAULT_MTLS_ENDPOINT + + flow_path = staticmethod(TransitionRouteGroupsClient.flow_path) + parse_flow_path = staticmethod(TransitionRouteGroupsClient.parse_flow_path) + intent_path = staticmethod(TransitionRouteGroupsClient.intent_path) + parse_intent_path = staticmethod(TransitionRouteGroupsClient.parse_intent_path) + page_path = staticmethod(TransitionRouteGroupsClient.page_path) + parse_page_path = staticmethod(TransitionRouteGroupsClient.parse_page_path) + transition_route_group_path = staticmethod(TransitionRouteGroupsClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(TransitionRouteGroupsClient.parse_transition_route_group_path) + webhook_path = staticmethod(TransitionRouteGroupsClient.webhook_path) + parse_webhook_path = staticmethod(TransitionRouteGroupsClient.parse_webhook_path) + common_billing_account_path = staticmethod(TransitionRouteGroupsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TransitionRouteGroupsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TransitionRouteGroupsClient.common_folder_path) + parse_common_folder_path = staticmethod(TransitionRouteGroupsClient.parse_common_folder_path) + common_organization_path = staticmethod(TransitionRouteGroupsClient.common_organization_path) + parse_common_organization_path = staticmethod(TransitionRouteGroupsClient.parse_common_organization_path) + common_project_path = staticmethod(TransitionRouteGroupsClient.common_project_path) + parse_common_project_path = staticmethod(TransitionRouteGroupsClient.parse_common_project_path) + common_location_path = staticmethod(TransitionRouteGroupsClient.common_location_path) + parse_common_location_path = staticmethod(TransitionRouteGroupsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TransitionRouteGroupsAsyncClient: The constructed client. + """ + return TransitionRouteGroupsClient.from_service_account_info.__func__(TransitionRouteGroupsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TransitionRouteGroupsAsyncClient: The constructed client. + """ + return TransitionRouteGroupsClient.from_service_account_file.__func__(TransitionRouteGroupsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> TransitionRouteGroupsTransport: + """Returns the transport used by the client instance. + + Returns: + TransitionRouteGroupsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(TransitionRouteGroupsClient).get_transport_class, type(TransitionRouteGroupsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, TransitionRouteGroupsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the transition route groups client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.TransitionRouteGroupsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = TransitionRouteGroupsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_transition_route_groups(self, + request: transition_route_group.ListTransitionRouteGroupsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransitionRouteGroupsAsyncPager: + r"""Returns the list of all transition route groups in + the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest`): + The request object. The request message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. + parent (:class:`str`): + Required. The flow to list all transition route groups + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.transition_route_groups.pagers.ListTransitionRouteGroupsAsyncPager: + The response message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = transition_route_group.ListTransitionRouteGroupsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_transition_route_groups, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTransitionRouteGroupsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_transition_route_group(self, + request: transition_route_group.GetTransitionRouteGroupRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transition_route_group.TransitionRouteGroup: + r"""Retrieves the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetTransitionRouteGroupRequest`): + The request object. The request message for + [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.GetTransitionRouteGroup]. + name (:class:`str`): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = transition_route_group.GetTransitionRouteGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_transition_route_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_transition_route_group(self, + request: gcdc_transition_route_group.CreateTransitionRouteGroupRequest = None, + *, + parent: str = None, + transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_transition_route_group.TransitionRouteGroup: + r"""Creates an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + in the specified flow. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateTransitionRouteGroupRequest`): + The request object. The request message for + [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.CreateTransitionRouteGroup]. + parent (:class:`str`): + Required. The flow to create an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + transition_route_group (:class:`google.cloud.dialogflowcx_v3.types.TransitionRouteGroup`): + Required. The transition route group + to create. + + This corresponds to the ``transition_route_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, transition_route_group]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if transition_route_group is not None: + request.transition_route_group = transition_route_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_transition_route_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_transition_route_group(self, + request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, + *, + transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_transition_route_group.TransitionRouteGroup: + r"""Updates the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateTransitionRouteGroupRequest`): + The request object. The request message for + [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.UpdateTransitionRouteGroup]. + transition_route_group (:class:`google.cloud.dialogflowcx_v3.types.TransitionRouteGroup`): + Required. The transition route group + to update. + + This corresponds to the ``transition_route_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The mask to control which fields get + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([transition_route_group, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if transition_route_group is not None: + request.transition_route_group = transition_route_group + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_transition_route_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("transition_route_group.name", request.transition_route_group.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_transition_route_group(self, + request: transition_route_group.DeleteTransitionRouteGroupRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteTransitionRouteGroupRequest`): + The request object. The request message for + [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.DeleteTransitionRouteGroup]. + name (:class:`str`): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + to delete. Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = transition_route_group.DeleteTransitionRouteGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_transition_route_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TransitionRouteGroupsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py new file mode 100644 index 00000000..33d7347e --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py @@ -0,0 +1,840 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.transition_route_groups import pagers +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import transition_route_group +from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TransitionRouteGroupsGrpcTransport +from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport + + +class TransitionRouteGroupsClientMeta(type): + """Metaclass for the TransitionRouteGroups client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[TransitionRouteGroupsTransport]] + _transport_registry["grpc"] = TransitionRouteGroupsGrpcTransport + _transport_registry["grpc_asyncio"] = TransitionRouteGroupsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[TransitionRouteGroupsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class TransitionRouteGroupsClient(metaclass=TransitionRouteGroupsClientMeta): + """Service for managing + [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TransitionRouteGroupsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + TransitionRouteGroupsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> TransitionRouteGroupsTransport: + """Returns the transport used by the client instance. + + Returns: + TransitionRouteGroupsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, TransitionRouteGroupsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the transition route groups client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, TransitionRouteGroupsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, TransitionRouteGroupsTransport): + # transport is a TransitionRouteGroupsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_transition_route_groups(self, + request: Union[transition_route_group.ListTransitionRouteGroupsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransitionRouteGroupsPager: + r"""Returns the list of all transition route groups in + the specified flow. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest, dict]): + The request object. The request message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. + parent (str): + Required. The flow to list all transition route groups + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.transition_route_groups.pagers.ListTransitionRouteGroupsPager: + The response message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a transition_route_group.ListTransitionRouteGroupsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, transition_route_group.ListTransitionRouteGroupsRequest): + request = transition_route_group.ListTransitionRouteGroupsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_transition_route_groups] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTransitionRouteGroupsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_transition_route_group(self, + request: Union[transition_route_group.GetTransitionRouteGroupRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transition_route_group.TransitionRouteGroup: + r"""Retrieves the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetTransitionRouteGroupRequest, dict]): + The request object. The request message for + [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.GetTransitionRouteGroup]. + name (str): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a transition_route_group.GetTransitionRouteGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, transition_route_group.GetTransitionRouteGroupRequest): + request = transition_route_group.GetTransitionRouteGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_transition_route_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_transition_route_group(self, + request: Union[gcdc_transition_route_group.CreateTransitionRouteGroupRequest, dict] = None, + *, + parent: str = None, + transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_transition_route_group.TransitionRouteGroup: + r"""Creates an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + in the specified flow. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateTransitionRouteGroupRequest, dict]): + The request object. The request message for + [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.CreateTransitionRouteGroup]. + parent (str): + Required. The flow to create an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + transition_route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): + Required. The transition route group + to create. + + This corresponds to the ``transition_route_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, transition_route_group]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_transition_route_group.CreateTransitionRouteGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_transition_route_group.CreateTransitionRouteGroupRequest): + request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if transition_route_group is not None: + request.transition_route_group = transition_route_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_transition_route_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_transition_route_group(self, + request: Union[gcdc_transition_route_group.UpdateTransitionRouteGroupRequest, dict] = None, + *, + transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_transition_route_group.TransitionRouteGroup: + r"""Updates the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateTransitionRouteGroupRequest, dict]): + The request object. The request message for + [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.UpdateTransitionRouteGroup]. + transition_route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): + Required. The transition route group + to update. + + This corresponds to the ``transition_route_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([transition_route_group, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_transition_route_group.UpdateTransitionRouteGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): + request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if transition_route_group is not None: + request.transition_route_group = transition_route_group + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_transition_route_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("transition_route_group.name", request.transition_route_group.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_transition_route_group(self, + request: Union[transition_route_group.DeleteTransitionRouteGroupRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteTransitionRouteGroupRequest, dict]): + The request object. The request message for + [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.DeleteTransitionRouteGroup]. + name (str): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + to delete. Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a transition_route_group.DeleteTransitionRouteGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, transition_route_group.DeleteTransitionRouteGroupRequest): + request = transition_route_group.DeleteTransitionRouteGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_transition_route_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TransitionRouteGroupsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py new file mode 100644 index 00000000..c31b3a1b --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import transition_route_group + + +class ListTransitionRouteGroupsPager: + """A pager for iterating through ``list_transition_route_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``transition_route_groups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTransitionRouteGroups`` requests and continue to iterate + through the ``transition_route_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., transition_route_group.ListTransitionRouteGroupsResponse], + request: transition_route_group.ListTransitionRouteGroupsRequest, + response: transition_route_group.ListTransitionRouteGroupsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = transition_route_group.ListTransitionRouteGroupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[transition_route_group.ListTransitionRouteGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[transition_route_group.TransitionRouteGroup]: + for page in self.pages: + yield from page.transition_route_groups + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTransitionRouteGroupsAsyncPager: + """A pager for iterating through ``list_transition_route_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``transition_route_groups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTransitionRouteGroups`` requests and continue to iterate + through the ``transition_route_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[transition_route_group.ListTransitionRouteGroupsResponse]], + request: transition_route_group.ListTransitionRouteGroupsRequest, + response: transition_route_group.ListTransitionRouteGroupsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = transition_route_group.ListTransitionRouteGroupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[transition_route_group.ListTransitionRouteGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[transition_route_group.TransitionRouteGroup]: + async def async_generator(): + async for page in self.pages: + for response in page.transition_route_groups: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py new file mode 100644 index 00000000..50e891f2 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import TransitionRouteGroupsTransport +from .grpc import TransitionRouteGroupsGrpcTransport +from .grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TransitionRouteGroupsTransport]] +_transport_registry['grpc'] = TransitionRouteGroupsGrpcTransport +_transport_registry['grpc_asyncio'] = TransitionRouteGroupsGrpcAsyncIOTransport + +__all__ = ( + 'TransitionRouteGroupsTransport', + 'TransitionRouteGroupsGrpcTransport', + 'TransitionRouteGroupsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py new file mode 100644 index 00000000..32ee9166 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import transition_route_group +from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class TransitionRouteGroupsTransport(abc.ABC): + """Abstract transport class for TransitionRouteGroups.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_transition_route_groups: gapic_v1.method.wrap_method( + self.list_transition_route_groups, + default_timeout=None, + client_info=client_info, + ), + self.get_transition_route_group: gapic_v1.method.wrap_method( + self.get_transition_route_group, + default_timeout=None, + client_info=client_info, + ), + self.create_transition_route_group: gapic_v1.method.wrap_method( + self.create_transition_route_group, + default_timeout=None, + client_info=client_info, + ), + self.update_transition_route_group: gapic_v1.method.wrap_method( + self.update_transition_route_group, + default_timeout=None, + client_info=client_info, + ), + self.delete_transition_route_group: gapic_v1.method.wrap_method( + self.delete_transition_route_group, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_transition_route_groups(self) -> Callable[ + [transition_route_group.ListTransitionRouteGroupsRequest], + Union[ + transition_route_group.ListTransitionRouteGroupsResponse, + Awaitable[transition_route_group.ListTransitionRouteGroupsResponse] + ]]: + raise NotImplementedError() + + @property + def get_transition_route_group(self) -> Callable[ + [transition_route_group.GetTransitionRouteGroupRequest], + Union[ + transition_route_group.TransitionRouteGroup, + Awaitable[transition_route_group.TransitionRouteGroup] + ]]: + raise NotImplementedError() + + @property + def create_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], + Union[ + gcdc_transition_route_group.TransitionRouteGroup, + Awaitable[gcdc_transition_route_group.TransitionRouteGroup] + ]]: + raise NotImplementedError() + + @property + def update_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], + Union[ + gcdc_transition_route_group.TransitionRouteGroup, + Awaitable[gcdc_transition_route_group.TransitionRouteGroup] + ]]: + raise NotImplementedError() + + @property + def delete_transition_route_group(self) -> Callable[ + [transition_route_group.DeleteTransitionRouteGroupRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'TransitionRouteGroupsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py new file mode 100644 index 00000000..91589bbd --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py @@ -0,0 +1,379 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import transition_route_group +from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import empty_pb2 # type: ignore +from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO + + +class TransitionRouteGroupsGrpcTransport(TransitionRouteGroupsTransport): + """gRPC backend transport for TransitionRouteGroups. + + Service for managing + [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_transition_route_groups(self) -> Callable[ + [transition_route_group.ListTransitionRouteGroupsRequest], + transition_route_group.ListTransitionRouteGroupsResponse]: + r"""Return a callable for the list transition route groups method over gRPC. + + Returns the list of all transition route groups in + the specified flow. + + Returns: + Callable[[~.ListTransitionRouteGroupsRequest], + ~.ListTransitionRouteGroupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_transition_route_groups' not in self._stubs: + self._stubs['list_transition_route_groups'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/ListTransitionRouteGroups', + request_serializer=transition_route_group.ListTransitionRouteGroupsRequest.serialize, + response_deserializer=transition_route_group.ListTransitionRouteGroupsResponse.deserialize, + ) + return self._stubs['list_transition_route_groups'] + + @property + def get_transition_route_group(self) -> Callable[ + [transition_route_group.GetTransitionRouteGroupRequest], + transition_route_group.TransitionRouteGroup]: + r"""Return a callable for the get transition route group method over gRPC. + + Retrieves the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Returns: + Callable[[~.GetTransitionRouteGroupRequest], + ~.TransitionRouteGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_transition_route_group' not in self._stubs: + self._stubs['get_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/GetTransitionRouteGroup', + request_serializer=transition_route_group.GetTransitionRouteGroupRequest.serialize, + response_deserializer=transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['get_transition_route_group'] + + @property + def create_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], + gcdc_transition_route_group.TransitionRouteGroup]: + r"""Return a callable for the create transition route group method over gRPC. + + Creates an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + in the specified flow. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateTransitionRouteGroupRequest], + ~.TransitionRouteGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_transition_route_group' not in self._stubs: + self._stubs['create_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/CreateTransitionRouteGroup', + request_serializer=gcdc_transition_route_group.CreateTransitionRouteGroupRequest.serialize, + response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['create_transition_route_group'] + + @property + def update_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], + gcdc_transition_route_group.TransitionRouteGroup]: + r"""Return a callable for the update transition route group method over gRPC. + + Updates the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateTransitionRouteGroupRequest], + ~.TransitionRouteGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_transition_route_group' not in self._stubs: + self._stubs['update_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/UpdateTransitionRouteGroup', + request_serializer=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest.serialize, + response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['update_transition_route_group'] + + @property + def delete_transition_route_group(self) -> Callable[ + [transition_route_group.DeleteTransitionRouteGroupRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete transition route group method over gRPC. + + Deletes the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteTransitionRouteGroupRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_transition_route_group' not in self._stubs: + self._stubs['delete_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/DeleteTransitionRouteGroup', + request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_transition_route_group'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'TransitionRouteGroupsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py new file mode 100644 index 00000000..5a9c60a2 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import transition_route_group +from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import empty_pb2 # type: ignore +from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO +from .grpc import TransitionRouteGroupsGrpcTransport + + +class TransitionRouteGroupsGrpcAsyncIOTransport(TransitionRouteGroupsTransport): + """gRPC AsyncIO backend transport for TransitionRouteGroups. + + Service for managing + [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_transition_route_groups(self) -> Callable[ + [transition_route_group.ListTransitionRouteGroupsRequest], + Awaitable[transition_route_group.ListTransitionRouteGroupsResponse]]: + r"""Return a callable for the list transition route groups method over gRPC. + + Returns the list of all transition route groups in + the specified flow. + + Returns: + Callable[[~.ListTransitionRouteGroupsRequest], + Awaitable[~.ListTransitionRouteGroupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_transition_route_groups' not in self._stubs: + self._stubs['list_transition_route_groups'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/ListTransitionRouteGroups', + request_serializer=transition_route_group.ListTransitionRouteGroupsRequest.serialize, + response_deserializer=transition_route_group.ListTransitionRouteGroupsResponse.deserialize, + ) + return self._stubs['list_transition_route_groups'] + + @property + def get_transition_route_group(self) -> Callable[ + [transition_route_group.GetTransitionRouteGroupRequest], + Awaitable[transition_route_group.TransitionRouteGroup]]: + r"""Return a callable for the get transition route group method over gRPC. + + Retrieves the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Returns: + Callable[[~.GetTransitionRouteGroupRequest], + Awaitable[~.TransitionRouteGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_transition_route_group' not in self._stubs: + self._stubs['get_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/GetTransitionRouteGroup', + request_serializer=transition_route_group.GetTransitionRouteGroupRequest.serialize, + response_deserializer=transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['get_transition_route_group'] + + @property + def create_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], + Awaitable[gcdc_transition_route_group.TransitionRouteGroup]]: + r"""Return a callable for the create transition route group method over gRPC. + + Creates an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + in the specified flow. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.CreateTransitionRouteGroupRequest], + Awaitable[~.TransitionRouteGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_transition_route_group' not in self._stubs: + self._stubs['create_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/CreateTransitionRouteGroup', + request_serializer=gcdc_transition_route_group.CreateTransitionRouteGroupRequest.serialize, + response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['create_transition_route_group'] + + @property + def update_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], + Awaitable[gcdc_transition_route_group.TransitionRouteGroup]]: + r"""Return a callable for the update transition route group method over gRPC. + + Updates the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.UpdateTransitionRouteGroupRequest], + Awaitable[~.TransitionRouteGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_transition_route_group' not in self._stubs: + self._stubs['update_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/UpdateTransitionRouteGroup', + request_serializer=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest.serialize, + response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['update_transition_route_group'] + + @property + def delete_transition_route_group(self) -> Callable[ + [transition_route_group.DeleteTransitionRouteGroupRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete transition route group method over gRPC. + + Deletes the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Note: You should always train a flow prior to sending it + queries. See the `training + documentation `__. + + Returns: + Callable[[~.DeleteTransitionRouteGroupRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_transition_route_group' not in self._stubs: + self._stubs['delete_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/DeleteTransitionRouteGroup', + request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_transition_route_group'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'TransitionRouteGroupsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/__init__.py new file mode 100644 index 00000000..630246bd --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import VersionsClient +from .async_client import VersionsAsyncClient + +__all__ = ( + 'VersionsClient', + 'VersionsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/async_client.py new file mode 100644 index 00000000..ff0ec35d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/async_client.py @@ -0,0 +1,708 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflowcx_v3.services.versions import pagers +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import version +from google.cloud.dialogflowcx_v3.types import version as gcdc_version +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport +from .client import VersionsClient + + +class VersionsAsyncClient: + """Service for managing + [Versions][google.cloud.dialogflow.cx.v3.Version]. + """ + + _client: VersionsClient + + DEFAULT_ENDPOINT = VersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VersionsClient.DEFAULT_MTLS_ENDPOINT + + version_path = staticmethod(VersionsClient.version_path) + parse_version_path = staticmethod(VersionsClient.parse_version_path) + common_billing_account_path = staticmethod(VersionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VersionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VersionsClient.common_folder_path) + parse_common_folder_path = staticmethod(VersionsClient.parse_common_folder_path) + common_organization_path = staticmethod(VersionsClient.common_organization_path) + parse_common_organization_path = staticmethod(VersionsClient.parse_common_organization_path) + common_project_path = staticmethod(VersionsClient.common_project_path) + parse_common_project_path = staticmethod(VersionsClient.parse_common_project_path) + common_location_path = staticmethod(VersionsClient.common_location_path) + parse_common_location_path = staticmethod(VersionsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_info.__func__(VersionsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_file.__func__(VersionsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VersionsTransport: + """Returns the transport used by the client instance. + + Returns: + VersionsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(VersionsClient).get_transport_class, type(VersionsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, VersionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the versions client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.VersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = VersionsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_versions(self, + request: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsAsyncPager: + r"""Returns the list of all versions in the specified + [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListVersionsRequest`): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. + parent (:class:`str`): + Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] + to list all versions for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.versions.pagers.ListVersionsAsyncPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = version.ListVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_versions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListVersionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_version(self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetVersionRequest`): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.cx.v3.Versions.GetVersion]. + name (:class:`str`): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3.Version]. + Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Version: + Represents a version of a flow. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = version.GetVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_version(self, + request: gcdc_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcdc_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in + the specified [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [CreateVersionOperationMetadata][google.cloud.dialogflow.cx.v3.CreateVersionOperationMetadata] + - ``response``: + [Version][google.cloud.dialogflow.cx.v3.Version] + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateVersionRequest`): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.cx.v3.Versions.CreateVersion]. + parent (:class:`str`): + Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] + to create an + [Version][google.cloud.dialogflow.cx.v3.Version] for. + Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (:class:`google.cloud.dialogflowcx_v3.types.Version`): + Required. The version to create. + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.Version` + Represents a version of a flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, version]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_version.CreateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + request.version = version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcdc_version.Version, + metadata_type=gcdc_version.CreateVersionOperationMetadata, + ) + + # Done; return the response. + return response + + async def update_version(self, + request: gcdc_version.UpdateVersionRequest = None, + *, + version: gcdc_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_version.Version: + r"""Updates the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateVersionRequest`): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.cx.v3.Versions.UpdateVersion]. + version (:class:`google.cloud.dialogflowcx_v3.types.Version`): + Required. The version to update. + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which fields get updated. + Currently only ``description`` and ``display_name`` can + be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Version: + Represents a version of a flow. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_version.UpdateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("version.name", request.version.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_version(self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteVersionRequest`): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.cx.v3.Versions.DeleteVersion]. + name (:class:`str`): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3.Version] to + delete. Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = version.DeleteVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def load_version(self, + request: version.LoadVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Loads resources in the specified version to the draft flow. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.LoadVersionRequest`): + The request object. The request message for + [Versions.LoadVersion][google.cloud.dialogflow.cx.v3.Versions.LoadVersion]. + name (:class:`str`): + Required. The + [Version][google.cloud.dialogflow.cx.v3.Version] to be + loaded to draft flow. Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = version.LoadVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.load_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/client.py new file mode 100644 index 00000000..f45ba713 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/client.py @@ -0,0 +1,905 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.dialogflowcx_v3.services.versions import pagers +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import version +from google.cloud.dialogflowcx_v3.types import version as gcdc_version +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VersionsGrpcTransport +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport + + +class VersionsClientMeta(type): + """Metaclass for the Versions client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] + _transport_registry["grpc"] = VersionsGrpcTransport + _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[VersionsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class VersionsClient(metaclass=VersionsClientMeta): + """Service for managing + [Versions][google.cloud.dialogflow.cx.v3.Version]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VersionsTransport: + """Returns the transport used by the client instance. + + Returns: + VersionsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, VersionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the versions client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, VersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, VersionsTransport): + # transport is a VersionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_versions(self, + request: Union[version.ListVersionsRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsPager: + r"""Returns the list of all versions in the specified + [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListVersionsRequest, dict]): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. + parent (str): + Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] + to list all versions for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.versions.pagers.ListVersionsPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a version.ListVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.ListVersionsRequest): + request = version.ListVersionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_versions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListVersionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_version(self, + request: Union[version.GetVersionRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetVersionRequest, dict]): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.cx.v3.Versions.GetVersion]. + name (str): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3.Version]. + Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Version: + Represents a version of a flow. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a version.GetVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.GetVersionRequest): + request = version.GetVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_version(self, + request: Union[gcdc_version.CreateVersionRequest, dict] = None, + *, + parent: str = None, + version: gcdc_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in + the specified [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [CreateVersionOperationMetadata][google.cloud.dialogflow.cx.v3.CreateVersionOperationMetadata] + - ``response``: + [Version][google.cloud.dialogflow.cx.v3.Version] + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateVersionRequest, dict]): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.cx.v3.Versions.CreateVersion]. + parent (str): + Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] + to create an + [Version][google.cloud.dialogflow.cx.v3.Version] for. + Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (google.cloud.dialogflowcx_v3.types.Version): + Required. The version to create. + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.Version` + Represents a version of a flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, version]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_version.CreateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_version.CreateVersionRequest): + request = gcdc_version.CreateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + request.version = version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcdc_version.Version, + metadata_type=gcdc_version.CreateVersionOperationMetadata, + ) + + # Done; return the response. + return response + + def update_version(self, + request: Union[gcdc_version.UpdateVersionRequest, dict] = None, + *, + version: gcdc_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_version.Version: + r"""Updates the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateVersionRequest, dict]): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.cx.v3.Versions.UpdateVersion]. + version (google.cloud.dialogflowcx_v3.types.Version): + Required. The version to update. + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields get updated. + Currently only ``description`` and ``display_name`` can + be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Version: + Represents a version of a flow. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_version.UpdateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_version.UpdateVersionRequest): + request = gcdc_version.UpdateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("version.name", request.version.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_version(self, + request: Union[version.DeleteVersionRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteVersionRequest, dict]): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.cx.v3.Versions.DeleteVersion]. + name (str): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3.Version] to + delete. Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a version.DeleteVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.DeleteVersionRequest): + request = version.DeleteVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def load_version(self, + request: Union[version.LoadVersionRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Loads resources in the specified version to the draft flow. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.LoadVersionRequest, dict]): + The request object. The request message for + [Versions.LoadVersion][google.cloud.dialogflow.cx.v3.Versions.LoadVersion]. + name (str): + Required. The + [Version][google.cloud.dialogflow.cx.v3.Version] to be + loaded to draft flow. Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a version.LoadVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.LoadVersionRequest): + request = version.LoadVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.load_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/pagers.py new file mode 100644 index 00000000..22a8056f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import version + + +class ListVersionsPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., version.ListVersionsResponse], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = version.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[version.Version]: + for page in self.pages: + yield from page.versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListVersionsAsyncPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[version.ListVersionsResponse]], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = version.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[version.Version]: + async def async_generator(): + async for page in self.pages: + for response in page.versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py new file mode 100644 index 00000000..dfb70ce9 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import VersionsTransport +from .grpc import VersionsGrpcTransport +from .grpc_asyncio import VersionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] +_transport_registry['grpc'] = VersionsGrpcTransport +_transport_registry['grpc_asyncio'] = VersionsGrpcAsyncIOTransport + +__all__ = ( + 'VersionsTransport', + 'VersionsGrpcTransport', + 'VersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/base.py new file mode 100644 index 00000000..60556f41 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/base.py @@ -0,0 +1,257 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import version +from google.cloud.dialogflowcx_v3.types import version as gcdc_version +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class VersionsTransport(abc.ABC): + """Abstract transport class for Versions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_versions: gapic_v1.method.wrap_method( + self.list_versions, + default_timeout=None, + client_info=client_info, + ), + self.get_version: gapic_v1.method.wrap_method( + self.get_version, + default_timeout=None, + client_info=client_info, + ), + self.create_version: gapic_v1.method.wrap_method( + self.create_version, + default_timeout=None, + client_info=client_info, + ), + self.update_version: gapic_v1.method.wrap_method( + self.update_version, + default_timeout=None, + client_info=client_info, + ), + self.delete_version: gapic_v1.method.wrap_method( + self.delete_version, + default_timeout=None, + client_info=client_info, + ), + self.load_version: gapic_v1.method.wrap_method( + self.load_version, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_versions(self) -> Callable[ + [version.ListVersionsRequest], + Union[ + version.ListVersionsResponse, + Awaitable[version.ListVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + Union[ + version.Version, + Awaitable[version.Version] + ]]: + raise NotImplementedError() + + @property + def create_version(self) -> Callable[ + [gcdc_version.CreateVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_version(self) -> Callable[ + [gcdc_version.UpdateVersionRequest], + Union[ + gcdc_version.Version, + Awaitable[gcdc_version.Version] + ]]: + raise NotImplementedError() + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def load_version(self) -> Callable[ + [version.LoadVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VersionsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py new file mode 100644 index 00000000..5d4e3b8d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py @@ -0,0 +1,431 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import version +from google.cloud.dialogflowcx_v3.types import version as gcdc_version +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO + + +class VersionsGrpcTransport(VersionsTransport): + """gRPC backend transport for Versions. + + Service for managing + [Versions][google.cloud.dialogflow.cx.v3.Version]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_versions(self) -> Callable[ + [version.ListVersionsRequest], + version.ListVersionsResponse]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions in the specified + [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + Returns: + Callable[[~.ListVersionsRequest], + ~.ListVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_versions' not in self._stubs: + self._stubs['list_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/ListVersions', + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs['list_versions'] + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + version.Version]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Returns: + Callable[[~.GetVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_version' not in self._stubs: + self._stubs['get_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcdc_version.CreateVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create version method over gRPC. + + Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in + the specified [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [CreateVersionOperationMetadata][google.cloud.dialogflow.cx.v3.CreateVersionOperationMetadata] + - ``response``: + [Version][google.cloud.dialogflow.cx.v3.Version] + + Returns: + Callable[[~.CreateVersionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/CreateVersion', + request_serializer=gcdc_version.CreateVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcdc_version.UpdateVersionRequest], + gcdc_version.Version]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Returns: + Callable[[~.UpdateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_version' not in self._stubs: + self._stubs['update_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/UpdateVersion', + request_serializer=gcdc_version.UpdateVersionRequest.serialize, + response_deserializer=gcdc_version.Version.deserialize, + ) + return self._stubs['update_version'] + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete version method over gRPC. + + Deletes the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Returns: + Callable[[~.DeleteVersionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_version' not in self._stubs: + self._stubs['delete_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + @property + def load_version(self) -> Callable[ + [version.LoadVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the load version method over gRPC. + + Loads resources in the specified version to the draft flow. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Returns: + Callable[[~.LoadVersionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'load_version' not in self._stubs: + self._stubs['load_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/LoadVersion', + request_serializer=version.LoadVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['load_version'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'VersionsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py new file mode 100644 index 00000000..51dff6ad --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py @@ -0,0 +1,436 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import version +from google.cloud.dialogflowcx_v3.types import version as gcdc_version +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO +from .grpc import VersionsGrpcTransport + + +class VersionsGrpcAsyncIOTransport(VersionsTransport): + """gRPC AsyncIO backend transport for Versions. + + Service for managing + [Versions][google.cloud.dialogflow.cx.v3.Version]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_versions(self) -> Callable[ + [version.ListVersionsRequest], + Awaitable[version.ListVersionsResponse]]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions in the specified + [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + Returns: + Callable[[~.ListVersionsRequest], + Awaitable[~.ListVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_versions' not in self._stubs: + self._stubs['list_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/ListVersions', + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs['list_versions'] + + @property + def get_version(self) -> Callable[ + [version.GetVersionRequest], + Awaitable[version.Version]]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Returns: + Callable[[~.GetVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_version' not in self._stubs: + self._stubs['get_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcdc_version.CreateVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create version method over gRPC. + + Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in + the specified [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: + [CreateVersionOperationMetadata][google.cloud.dialogflow.cx.v3.CreateVersionOperationMetadata] + - ``response``: + [Version][google.cloud.dialogflow.cx.v3.Version] + + Returns: + Callable[[~.CreateVersionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/CreateVersion', + request_serializer=gcdc_version.CreateVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcdc_version.UpdateVersionRequest], + Awaitable[gcdc_version.Version]]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Returns: + Callable[[~.UpdateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_version' not in self._stubs: + self._stubs['update_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/UpdateVersion', + request_serializer=gcdc_version.UpdateVersionRequest.serialize, + response_deserializer=gcdc_version.Version.deserialize, + ) + return self._stubs['update_version'] + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete version method over gRPC. + + Deletes the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Returns: + Callable[[~.DeleteVersionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_version' not in self._stubs: + self._stubs['delete_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + @property + def load_version(self) -> Callable[ + [version.LoadVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the load version method over gRPC. + + Loads resources in the specified version to the draft flow. + + This method is a `long-running + operation `__. + The returned ``Operation`` type has the following + method-specific fields: + + - ``metadata``: An empty `Struct + message `__ + - ``response``: An `Empty + message `__ + + Returns: + Callable[[~.LoadVersionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'load_version' not in self._stubs: + self._stubs['load_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/LoadVersion', + request_serializer=version.LoadVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['load_version'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'VersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py new file mode 100644 index 00000000..8ace8262 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import WebhooksClient +from .async_client import WebhooksAsyncClient + +__all__ = ( + 'WebhooksClient', + 'WebhooksAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py new file mode 100644 index 00000000..7efd4f4d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py @@ -0,0 +1,583 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.webhooks import pagers +from google.cloud.dialogflowcx_v3.types import webhook +from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport +from .client import WebhooksClient + + +class WebhooksAsyncClient: + """Service for managing + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook]. + """ + + _client: WebhooksClient + + DEFAULT_ENDPOINT = WebhooksClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WebhooksClient.DEFAULT_MTLS_ENDPOINT + + service_path = staticmethod(WebhooksClient.service_path) + parse_service_path = staticmethod(WebhooksClient.parse_service_path) + webhook_path = staticmethod(WebhooksClient.webhook_path) + parse_webhook_path = staticmethod(WebhooksClient.parse_webhook_path) + common_billing_account_path = staticmethod(WebhooksClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WebhooksClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WebhooksClient.common_folder_path) + parse_common_folder_path = staticmethod(WebhooksClient.parse_common_folder_path) + common_organization_path = staticmethod(WebhooksClient.common_organization_path) + parse_common_organization_path = staticmethod(WebhooksClient.parse_common_organization_path) + common_project_path = staticmethod(WebhooksClient.common_project_path) + parse_common_project_path = staticmethod(WebhooksClient.parse_common_project_path) + common_location_path = staticmethod(WebhooksClient.common_location_path) + parse_common_location_path = staticmethod(WebhooksClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebhooksAsyncClient: The constructed client. + """ + return WebhooksClient.from_service_account_info.__func__(WebhooksAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebhooksAsyncClient: The constructed client. + """ + return WebhooksClient.from_service_account_file.__func__(WebhooksAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> WebhooksTransport: + """Returns the transport used by the client instance. + + Returns: + WebhooksTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(WebhooksClient).get_transport_class, type(WebhooksClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, WebhooksTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the webhooks client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.WebhooksTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = WebhooksClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_webhooks(self, + request: webhook.ListWebhooksRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWebhooksAsyncPager: + r"""Returns the list of all webhooks in the specified + agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListWebhooksRequest`): + The request object. The request message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. + parent (:class:`str`): + Required. The agent to list all webhooks for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.webhooks.pagers.ListWebhooksAsyncPager: + The response message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = webhook.ListWebhooksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_webhooks, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListWebhooksAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_webhook(self, + request: webhook.GetWebhookRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> webhook.Webhook: + r"""Retrieves the specified webhook. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetWebhookRequest`): + The request object. The request message for + [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3.Webhooks.GetWebhook]. + name (:class:`str`): + Required. The name of the webhook. Format: + ``projects//locations//agents//webhooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = webhook.GetWebhookRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_webhook(self, + request: gcdc_webhook.CreateWebhookRequest = None, + *, + parent: str = None, + webhook: gcdc_webhook.Webhook = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_webhook.Webhook: + r"""Creates a webhook in the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateWebhookRequest`): + The request object. The request message for + [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.CreateWebhook]. + parent (:class:`str`): + Required. The agent to create a webhook for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + webhook (:class:`google.cloud.dialogflowcx_v3.types.Webhook`): + Required. The webhook to create. + This corresponds to the ``webhook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, webhook]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_webhook.CreateWebhookRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if webhook is not None: + request.webhook = webhook + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_webhook(self, + request: gcdc_webhook.UpdateWebhookRequest = None, + *, + webhook: gcdc_webhook.Webhook = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_webhook.Webhook: + r"""Updates the specified webhook. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateWebhookRequest`): + The request object. The request message for + [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.UpdateWebhook]. + webhook (:class:`google.cloud.dialogflowcx_v3.types.Webhook`): + Required. The webhook to update. + This corresponds to the ``webhook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The mask to control which fields get + updated. If the mask is not present, all + fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([webhook, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_webhook.UpdateWebhookRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if webhook is not None: + request.webhook = webhook + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("webhook.name", request.webhook.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_webhook(self, + request: webhook.DeleteWebhookRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified webhook. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteWebhookRequest`): + The request object. The request message for + [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3.Webhooks.DeleteWebhook]. + name (:class:`str`): + Required. The name of the webhook to delete. Format: + ``projects//locations//agents//webhooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = webhook.DeleteWebhookRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "WebhooksAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/client.py new file mode 100644 index 00000000..212398bd --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/client.py @@ -0,0 +1,789 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.services.webhooks import pagers +from google.cloud.dialogflowcx_v3.types import webhook +from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WebhooksGrpcTransport +from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport + + +class WebhooksClientMeta(type): + """Metaclass for the Webhooks client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[WebhooksTransport]] + _transport_registry["grpc"] = WebhooksGrpcTransport + _transport_registry["grpc_asyncio"] = WebhooksGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[WebhooksTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class WebhooksClient(metaclass=WebhooksClientMeta): + """Service for managing + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebhooksClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WebhooksClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> WebhooksTransport: + """Returns the transport used by the client instance. + + Returns: + WebhooksTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def service_path(project: str,location: str,namespace: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, WebhooksTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the webhooks client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, WebhooksTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, WebhooksTransport): + # transport is a WebhooksTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_webhooks(self, + request: Union[webhook.ListWebhooksRequest, dict] = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWebhooksPager: + r"""Returns the list of all webhooks in the specified + agent. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.ListWebhooksRequest, dict]): + The request object. The request message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. + parent (str): + Required. The agent to list all webhooks for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.webhooks.pagers.ListWebhooksPager: + The response message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a webhook.ListWebhooksRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, webhook.ListWebhooksRequest): + request = webhook.ListWebhooksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_webhooks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListWebhooksPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_webhook(self, + request: Union[webhook.GetWebhookRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> webhook.Webhook: + r"""Retrieves the specified webhook. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.GetWebhookRequest, dict]): + The request object. The request message for + [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3.Webhooks.GetWebhook]. + name (str): + Required. The name of the webhook. Format: + ``projects//locations//agents//webhooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a webhook.GetWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, webhook.GetWebhookRequest): + request = webhook.GetWebhookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_webhook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_webhook(self, + request: Union[gcdc_webhook.CreateWebhookRequest, dict] = None, + *, + parent: str = None, + webhook: gcdc_webhook.Webhook = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_webhook.Webhook: + r"""Creates a webhook in the specified agent. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.CreateWebhookRequest, dict]): + The request object. The request message for + [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.CreateWebhook]. + parent (str): + Required. The agent to create a webhook for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + webhook (google.cloud.dialogflowcx_v3.types.Webhook): + Required. The webhook to create. + This corresponds to the ``webhook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, webhook]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_webhook.CreateWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_webhook.CreateWebhookRequest): + request = gcdc_webhook.CreateWebhookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if webhook is not None: + request.webhook = webhook + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_webhook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_webhook(self, + request: Union[gcdc_webhook.UpdateWebhookRequest, dict] = None, + *, + webhook: gcdc_webhook.Webhook = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_webhook.Webhook: + r"""Updates the specified webhook. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.UpdateWebhookRequest, dict]): + The request object. The request message for + [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.UpdateWebhook]. + webhook (google.cloud.dialogflowcx_v3.types.Webhook): + Required. The webhook to update. + This corresponds to the ``webhook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get + updated. If the mask is not present, all + fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([webhook, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_webhook.UpdateWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_webhook.UpdateWebhookRequest): + request = gcdc_webhook.UpdateWebhookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if webhook is not None: + request.webhook = webhook + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_webhook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("webhook.name", request.webhook.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_webhook(self, + request: Union[webhook.DeleteWebhookRequest, dict] = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified webhook. + + Args: + request (Union[google.cloud.dialogflowcx_v3.types.DeleteWebhookRequest, dict]): + The request object. The request message for + [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3.Webhooks.DeleteWebhook]. + name (str): + Required. The name of the webhook to delete. Format: + ``projects//locations//agents//webhooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a webhook.DeleteWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, webhook.DeleteWebhookRequest): + request = webhook.DeleteWebhookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_webhook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "WebhooksClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py new file mode 100644 index 00000000..0eeea4c0 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.dialogflowcx_v3.types import webhook + + +class ListWebhooksPager: + """A pager for iterating through ``list_webhooks`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListWebhooksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``webhooks`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWebhooks`` requests and continue to iterate + through the ``webhooks`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListWebhooksResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., webhook.ListWebhooksResponse], + request: webhook.ListWebhooksRequest, + response: webhook.ListWebhooksResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListWebhooksRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListWebhooksResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = webhook.ListWebhooksRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[webhook.ListWebhooksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[webhook.Webhook]: + for page in self.pages: + yield from page.webhooks + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWebhooksAsyncPager: + """A pager for iterating through ``list_webhooks`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListWebhooksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``webhooks`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWebhooks`` requests and continue to iterate + through the ``webhooks`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListWebhooksResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[webhook.ListWebhooksResponse]], + request: webhook.ListWebhooksRequest, + response: webhook.ListWebhooksResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListWebhooksRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListWebhooksResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = webhook.ListWebhooksRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[webhook.ListWebhooksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[webhook.Webhook]: + async def async_generator(): + async for page in self.pages: + for response in page.webhooks: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py new file mode 100644 index 00000000..6006a6e7 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import WebhooksTransport +from .grpc import WebhooksGrpcTransport +from .grpc_asyncio import WebhooksGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WebhooksTransport]] +_transport_registry['grpc'] = WebhooksGrpcTransport +_transport_registry['grpc_asyncio'] = WebhooksGrpcAsyncIOTransport + +__all__ = ( + 'WebhooksTransport', + 'WebhooksGrpcTransport', + 'WebhooksGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py new file mode 100644 index 00000000..06b9cc13 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflowcx_v3.types import webhook +from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class WebhooksTransport(abc.ABC): + """Abstract transport class for Webhooks.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ) + + DEFAULT_HOST: str = 'dialogflow.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_webhooks: gapic_v1.method.wrap_method( + self.list_webhooks, + default_timeout=None, + client_info=client_info, + ), + self.get_webhook: gapic_v1.method.wrap_method( + self.get_webhook, + default_timeout=None, + client_info=client_info, + ), + self.create_webhook: gapic_v1.method.wrap_method( + self.create_webhook, + default_timeout=None, + client_info=client_info, + ), + self.update_webhook: gapic_v1.method.wrap_method( + self.update_webhook, + default_timeout=None, + client_info=client_info, + ), + self.delete_webhook: gapic_v1.method.wrap_method( + self.delete_webhook, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_webhooks(self) -> Callable[ + [webhook.ListWebhooksRequest], + Union[ + webhook.ListWebhooksResponse, + Awaitable[webhook.ListWebhooksResponse] + ]]: + raise NotImplementedError() + + @property + def get_webhook(self) -> Callable[ + [webhook.GetWebhookRequest], + Union[ + webhook.Webhook, + Awaitable[webhook.Webhook] + ]]: + raise NotImplementedError() + + @property + def create_webhook(self) -> Callable[ + [gcdc_webhook.CreateWebhookRequest], + Union[ + gcdc_webhook.Webhook, + Awaitable[gcdc_webhook.Webhook] + ]]: + raise NotImplementedError() + + @property + def update_webhook(self) -> Callable[ + [gcdc_webhook.UpdateWebhookRequest], + Union[ + gcdc_webhook.Webhook, + Awaitable[gcdc_webhook.Webhook] + ]]: + raise NotImplementedError() + + @property + def delete_webhook(self) -> Callable[ + [webhook.DeleteWebhookRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'WebhooksTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py new file mode 100644 index 00000000..1fe199d2 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import webhook +from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook +from google.protobuf import empty_pb2 # type: ignore +from .base import WebhooksTransport, DEFAULT_CLIENT_INFO + + +class WebhooksGrpcTransport(WebhooksTransport): + """gRPC backend transport for Webhooks. + + Service for managing + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_webhooks(self) -> Callable[ + [webhook.ListWebhooksRequest], + webhook.ListWebhooksResponse]: + r"""Return a callable for the list webhooks method over gRPC. + + Returns the list of all webhooks in the specified + agent. + + Returns: + Callable[[~.ListWebhooksRequest], + ~.ListWebhooksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_webhooks' not in self._stubs: + self._stubs['list_webhooks'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/ListWebhooks', + request_serializer=webhook.ListWebhooksRequest.serialize, + response_deserializer=webhook.ListWebhooksResponse.deserialize, + ) + return self._stubs['list_webhooks'] + + @property + def get_webhook(self) -> Callable[ + [webhook.GetWebhookRequest], + webhook.Webhook]: + r"""Return a callable for the get webhook method over gRPC. + + Retrieves the specified webhook. + + Returns: + Callable[[~.GetWebhookRequest], + ~.Webhook]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_webhook' not in self._stubs: + self._stubs['get_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/GetWebhook', + request_serializer=webhook.GetWebhookRequest.serialize, + response_deserializer=webhook.Webhook.deserialize, + ) + return self._stubs['get_webhook'] + + @property + def create_webhook(self) -> Callable[ + [gcdc_webhook.CreateWebhookRequest], + gcdc_webhook.Webhook]: + r"""Return a callable for the create webhook method over gRPC. + + Creates a webhook in the specified agent. + + Returns: + Callable[[~.CreateWebhookRequest], + ~.Webhook]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_webhook' not in self._stubs: + self._stubs['create_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/CreateWebhook', + request_serializer=gcdc_webhook.CreateWebhookRequest.serialize, + response_deserializer=gcdc_webhook.Webhook.deserialize, + ) + return self._stubs['create_webhook'] + + @property + def update_webhook(self) -> Callable[ + [gcdc_webhook.UpdateWebhookRequest], + gcdc_webhook.Webhook]: + r"""Return a callable for the update webhook method over gRPC. + + Updates the specified webhook. + + Returns: + Callable[[~.UpdateWebhookRequest], + ~.Webhook]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_webhook' not in self._stubs: + self._stubs['update_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/UpdateWebhook', + request_serializer=gcdc_webhook.UpdateWebhookRequest.serialize, + response_deserializer=gcdc_webhook.Webhook.deserialize, + ) + return self._stubs['update_webhook'] + + @property + def delete_webhook(self) -> Callable[ + [webhook.DeleteWebhookRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete webhook method over gRPC. + + Deletes the specified webhook. + + Returns: + Callable[[~.DeleteWebhookRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_webhook' not in self._stubs: + self._stubs['delete_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/DeleteWebhook', + request_serializer=webhook.DeleteWebhookRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_webhook'] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'WebhooksGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py new file mode 100644 index 00000000..71483917 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py @@ -0,0 +1,367 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflowcx_v3.types import webhook +from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook +from google.protobuf import empty_pb2 # type: ignore +from .base import WebhooksTransport, DEFAULT_CLIENT_INFO +from .grpc import WebhooksGrpcTransport + + +class WebhooksGrpcAsyncIOTransport(WebhooksTransport): + """gRPC AsyncIO backend transport for Webhooks. + + Service for managing + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'dialogflow.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_webhooks(self) -> Callable[ + [webhook.ListWebhooksRequest], + Awaitable[webhook.ListWebhooksResponse]]: + r"""Return a callable for the list webhooks method over gRPC. + + Returns the list of all webhooks in the specified + agent. + + Returns: + Callable[[~.ListWebhooksRequest], + Awaitable[~.ListWebhooksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_webhooks' not in self._stubs: + self._stubs['list_webhooks'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/ListWebhooks', + request_serializer=webhook.ListWebhooksRequest.serialize, + response_deserializer=webhook.ListWebhooksResponse.deserialize, + ) + return self._stubs['list_webhooks'] + + @property + def get_webhook(self) -> Callable[ + [webhook.GetWebhookRequest], + Awaitable[webhook.Webhook]]: + r"""Return a callable for the get webhook method over gRPC. + + Retrieves the specified webhook. + + Returns: + Callable[[~.GetWebhookRequest], + Awaitable[~.Webhook]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_webhook' not in self._stubs: + self._stubs['get_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/GetWebhook', + request_serializer=webhook.GetWebhookRequest.serialize, + response_deserializer=webhook.Webhook.deserialize, + ) + return self._stubs['get_webhook'] + + @property + def create_webhook(self) -> Callable[ + [gcdc_webhook.CreateWebhookRequest], + Awaitable[gcdc_webhook.Webhook]]: + r"""Return a callable for the create webhook method over gRPC. + + Creates a webhook in the specified agent. + + Returns: + Callable[[~.CreateWebhookRequest], + Awaitable[~.Webhook]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_webhook' not in self._stubs: + self._stubs['create_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/CreateWebhook', + request_serializer=gcdc_webhook.CreateWebhookRequest.serialize, + response_deserializer=gcdc_webhook.Webhook.deserialize, + ) + return self._stubs['create_webhook'] + + @property + def update_webhook(self) -> Callable[ + [gcdc_webhook.UpdateWebhookRequest], + Awaitable[gcdc_webhook.Webhook]]: + r"""Return a callable for the update webhook method over gRPC. + + Updates the specified webhook. + + Returns: + Callable[[~.UpdateWebhookRequest], + Awaitable[~.Webhook]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_webhook' not in self._stubs: + self._stubs['update_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/UpdateWebhook', + request_serializer=gcdc_webhook.UpdateWebhookRequest.serialize, + response_deserializer=gcdc_webhook.Webhook.deserialize, + ) + return self._stubs['update_webhook'] + + @property + def delete_webhook(self) -> Callable[ + [webhook.DeleteWebhookRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete webhook method over gRPC. + + Deletes the specified webhook. + + Returns: + Callable[[~.DeleteWebhookRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_webhook' not in self._stubs: + self._stubs['delete_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/DeleteWebhook', + request_serializer=webhook.DeleteWebhookRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_webhook'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'WebhooksGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/__init__.py new file mode 100644 index 00000000..9887738f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/__init__.py @@ -0,0 +1,454 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .advanced_settings import ( + AdvancedSettings, +) +from .agent import ( + Agent, + AgentValidationResult, + CreateAgentRequest, + DeleteAgentRequest, + ExportAgentRequest, + ExportAgentResponse, + GetAgentRequest, + GetAgentValidationResultRequest, + ListAgentsRequest, + ListAgentsResponse, + RestoreAgentRequest, + SpeechToTextSettings, + UpdateAgentRequest, + ValidateAgentRequest, +) +from .audio_config import ( + InputAudioConfig, + OutputAudioConfig, + SpeechWordInfo, + SynthesizeSpeechConfig, + VoiceSelectionParams, + AudioEncoding, + OutputAudioEncoding, + SpeechModelVariant, + SsmlVoiceGender, +) +from .deployment import ( + Deployment, + GetDeploymentRequest, + ListDeploymentsRequest, + ListDeploymentsResponse, +) +from .entity_type import ( + CreateEntityTypeRequest, + DeleteEntityTypeRequest, + EntityType, + GetEntityTypeRequest, + ListEntityTypesRequest, + ListEntityTypesResponse, + UpdateEntityTypeRequest, +) +from .environment import ( + ContinuousTestResult, + CreateEnvironmentRequest, + DeleteEnvironmentRequest, + DeployFlowMetadata, + DeployFlowRequest, + DeployFlowResponse, + Environment, + GetEnvironmentRequest, + ListContinuousTestResultsRequest, + ListContinuousTestResultsResponse, + ListEnvironmentsRequest, + ListEnvironmentsResponse, + LookupEnvironmentHistoryRequest, + LookupEnvironmentHistoryResponse, + RunContinuousTestMetadata, + RunContinuousTestRequest, + RunContinuousTestResponse, + UpdateEnvironmentRequest, +) +from .experiment import ( + CreateExperimentRequest, + DeleteExperimentRequest, + Experiment, + GetExperimentRequest, + ListExperimentsRequest, + ListExperimentsResponse, + RolloutConfig, + RolloutState, + StartExperimentRequest, + StopExperimentRequest, + UpdateExperimentRequest, + VariantsHistory, + VersionVariants, +) +from .flow import ( + CreateFlowRequest, + DeleteFlowRequest, + ExportFlowRequest, + ExportFlowResponse, + Flow, + FlowValidationResult, + GetFlowRequest, + GetFlowValidationResultRequest, + ImportFlowRequest, + ImportFlowResponse, + ListFlowsRequest, + ListFlowsResponse, + NluSettings, + TrainFlowRequest, + UpdateFlowRequest, + ValidateFlowRequest, +) +from .fulfillment import ( + Fulfillment, +) +from .intent import ( + CreateIntentRequest, + DeleteIntentRequest, + GetIntentRequest, + Intent, + ListIntentsRequest, + ListIntentsResponse, + UpdateIntentRequest, + IntentView, +) +from .page import ( + CreatePageRequest, + DeletePageRequest, + EventHandler, + Form, + GetPageRequest, + ListPagesRequest, + ListPagesResponse, + Page, + TransitionRoute, + UpdatePageRequest, +) +from .response_message import ( + ResponseMessage, +) +from .security_settings import ( + CreateSecuritySettingsRequest, + DeleteSecuritySettingsRequest, + GetSecuritySettingsRequest, + ListSecuritySettingsRequest, + ListSecuritySettingsResponse, + SecuritySettings, + UpdateSecuritySettingsRequest, +) +from .session import ( + AudioInput, + DetectIntentRequest, + DetectIntentResponse, + DtmfInput, + EventInput, + FulfillIntentRequest, + FulfillIntentResponse, + IntentInput, + Match, + MatchIntentRequest, + MatchIntentResponse, + QueryInput, + QueryParameters, + QueryResult, + SentimentAnalysisResult, + StreamingDetectIntentRequest, + StreamingDetectIntentResponse, + StreamingRecognitionResult, + TextInput, +) +from .session_entity_type import ( + CreateSessionEntityTypeRequest, + DeleteSessionEntityTypeRequest, + GetSessionEntityTypeRequest, + ListSessionEntityTypesRequest, + ListSessionEntityTypesResponse, + SessionEntityType, + UpdateSessionEntityTypeRequest, +) +from .test_case import ( + BatchDeleteTestCasesRequest, + BatchRunTestCasesMetadata, + BatchRunTestCasesRequest, + BatchRunTestCasesResponse, + CalculateCoverageRequest, + CalculateCoverageResponse, + ConversationTurn, + CreateTestCaseRequest, + ExportTestCasesMetadata, + ExportTestCasesRequest, + ExportTestCasesResponse, + GetTestCaseRequest, + GetTestCaseResultRequest, + ImportTestCasesMetadata, + ImportTestCasesRequest, + ImportTestCasesResponse, + IntentCoverage, + ListTestCaseResultsRequest, + ListTestCaseResultsResponse, + ListTestCasesRequest, + ListTestCasesResponse, + RunTestCaseMetadata, + RunTestCaseRequest, + RunTestCaseResponse, + TestCase, + TestCaseError, + TestCaseResult, + TestConfig, + TestError, + TestRunDifference, + TransitionCoverage, + TransitionRouteGroupCoverage, + UpdateTestCaseRequest, + TestResult, +) +from .transition_route_group import ( + CreateTransitionRouteGroupRequest, + DeleteTransitionRouteGroupRequest, + GetTransitionRouteGroupRequest, + ListTransitionRouteGroupsRequest, + ListTransitionRouteGroupsResponse, + TransitionRouteGroup, + UpdateTransitionRouteGroupRequest, +) +from .validation_message import ( + ResourceName, + ValidationMessage, +) +from .version import ( + CreateVersionOperationMetadata, + CreateVersionRequest, + DeleteVersionRequest, + GetVersionRequest, + ListVersionsRequest, + ListVersionsResponse, + LoadVersionRequest, + UpdateVersionRequest, + Version, +) +from .webhook import ( + CreateWebhookRequest, + DeleteWebhookRequest, + GetWebhookRequest, + ListWebhooksRequest, + ListWebhooksResponse, + PageInfo, + SessionInfo, + UpdateWebhookRequest, + Webhook, + WebhookRequest, + WebhookResponse, +) + +__all__ = ( + 'AdvancedSettings', + 'Agent', + 'AgentValidationResult', + 'CreateAgentRequest', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'GetAgentRequest', + 'GetAgentValidationResultRequest', + 'ListAgentsRequest', + 'ListAgentsResponse', + 'RestoreAgentRequest', + 'SpeechToTextSettings', + 'UpdateAgentRequest', + 'ValidateAgentRequest', + 'InputAudioConfig', + 'OutputAudioConfig', + 'SpeechWordInfo', + 'SynthesizeSpeechConfig', + 'VoiceSelectionParams', + 'AudioEncoding', + 'OutputAudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'Deployment', + 'GetDeploymentRequest', + 'ListDeploymentsRequest', + 'ListDeploymentsResponse', + 'CreateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'EntityType', + 'GetEntityTypeRequest', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'UpdateEntityTypeRequest', + 'ContinuousTestResult', + 'CreateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'DeployFlowMetadata', + 'DeployFlowRequest', + 'DeployFlowResponse', + 'Environment', + 'GetEnvironmentRequest', + 'ListContinuousTestResultsRequest', + 'ListContinuousTestResultsResponse', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LookupEnvironmentHistoryRequest', + 'LookupEnvironmentHistoryResponse', + 'RunContinuousTestMetadata', + 'RunContinuousTestRequest', + 'RunContinuousTestResponse', + 'UpdateEnvironmentRequest', + 'CreateExperimentRequest', + 'DeleteExperimentRequest', + 'Experiment', + 'GetExperimentRequest', + 'ListExperimentsRequest', + 'ListExperimentsResponse', + 'RolloutConfig', + 'RolloutState', + 'StartExperimentRequest', + 'StopExperimentRequest', + 'UpdateExperimentRequest', + 'VariantsHistory', + 'VersionVariants', + 'CreateFlowRequest', + 'DeleteFlowRequest', + 'ExportFlowRequest', + 'ExportFlowResponse', + 'Flow', + 'FlowValidationResult', + 'GetFlowRequest', + 'GetFlowValidationResultRequest', + 'ImportFlowRequest', + 'ImportFlowResponse', + 'ListFlowsRequest', + 'ListFlowsResponse', + 'NluSettings', + 'TrainFlowRequest', + 'UpdateFlowRequest', + 'ValidateFlowRequest', + 'Fulfillment', + 'CreateIntentRequest', + 'DeleteIntentRequest', + 'GetIntentRequest', + 'Intent', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'UpdateIntentRequest', + 'IntentView', + 'CreatePageRequest', + 'DeletePageRequest', + 'EventHandler', + 'Form', + 'GetPageRequest', + 'ListPagesRequest', + 'ListPagesResponse', + 'Page', + 'TransitionRoute', + 'UpdatePageRequest', + 'ResponseMessage', + 'CreateSecuritySettingsRequest', + 'DeleteSecuritySettingsRequest', + 'GetSecuritySettingsRequest', + 'ListSecuritySettingsRequest', + 'ListSecuritySettingsResponse', + 'SecuritySettings', + 'UpdateSecuritySettingsRequest', + 'AudioInput', + 'DetectIntentRequest', + 'DetectIntentResponse', + 'DtmfInput', + 'EventInput', + 'FulfillIntentRequest', + 'FulfillIntentResponse', + 'IntentInput', + 'Match', + 'MatchIntentRequest', + 'MatchIntentResponse', + 'QueryInput', + 'QueryParameters', + 'QueryResult', + 'SentimentAnalysisResult', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'TextInput', + 'CreateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + 'GetSessionEntityTypeRequest', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'SessionEntityType', + 'UpdateSessionEntityTypeRequest', + 'BatchDeleteTestCasesRequest', + 'BatchRunTestCasesMetadata', + 'BatchRunTestCasesRequest', + 'BatchRunTestCasesResponse', + 'CalculateCoverageRequest', + 'CalculateCoverageResponse', + 'ConversationTurn', + 'CreateTestCaseRequest', + 'ExportTestCasesMetadata', + 'ExportTestCasesRequest', + 'ExportTestCasesResponse', + 'GetTestCaseRequest', + 'GetTestCaseResultRequest', + 'ImportTestCasesMetadata', + 'ImportTestCasesRequest', + 'ImportTestCasesResponse', + 'IntentCoverage', + 'ListTestCaseResultsRequest', + 'ListTestCaseResultsResponse', + 'ListTestCasesRequest', + 'ListTestCasesResponse', + 'RunTestCaseMetadata', + 'RunTestCaseRequest', + 'RunTestCaseResponse', + 'TestCase', + 'TestCaseError', + 'TestCaseResult', + 'TestConfig', + 'TestError', + 'TestRunDifference', + 'TransitionCoverage', + 'TransitionRouteGroupCoverage', + 'UpdateTestCaseRequest', + 'TestResult', + 'CreateTransitionRouteGroupRequest', + 'DeleteTransitionRouteGroupRequest', + 'GetTransitionRouteGroupRequest', + 'ListTransitionRouteGroupsRequest', + 'ListTransitionRouteGroupsResponse', + 'TransitionRouteGroup', + 'UpdateTransitionRouteGroupRequest', + 'ResourceName', + 'ValidationMessage', + 'CreateVersionOperationMetadata', + 'CreateVersionRequest', + 'DeleteVersionRequest', + 'GetVersionRequest', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'LoadVersionRequest', + 'UpdateVersionRequest', + 'Version', + 'CreateWebhookRequest', + 'DeleteWebhookRequest', + 'GetWebhookRequest', + 'ListWebhooksRequest', + 'ListWebhooksResponse', + 'PageInfo', + 'SessionInfo', + 'UpdateWebhookRequest', + 'Webhook', + 'WebhookRequest', + 'WebhookResponse', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/advanced_settings.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/advanced_settings.py new file mode 100644 index 00000000..bdd81de6 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/advanced_settings.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'AdvancedSettings', + }, +) + + +class AdvancedSettings(proto.Message): + r"""Hierarchical advanced settings for + agent/flow/page/fulfillment/parameter. Settings exposed at lower + level overrides the settings exposed at higher level. + + Hierarchy: Agent->Flow->Page->Fulfillment/Parameter. + + Attributes: + logging_settings (google.cloud.dialogflowcx_v3.types.AdvancedSettings.LoggingSettings): + Settings for logging. + Settings for Dialogflow History, Contact Center + messages, StackDriver logs, and speech logging. + Exposed at the following levels: + - Agent level. + """ + + class LoggingSettings(proto.Message): + r"""Define behaviors on logging. + + Attributes: + enable_stackdriver_logging (bool): + If true, StackDriver logging is currently + enabled. + enable_interaction_logging (bool): + If true, DF Interaction logging is currently + enabled. + """ + + enable_stackdriver_logging = proto.Field( + proto.BOOL, + number=2, + ) + enable_interaction_logging = proto.Field( + proto.BOOL, + number=3, + ) + + logging_settings = proto.Field( + proto.MESSAGE, + number=6, + message=LoggingSettings, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/agent.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/agent.py new file mode 100644 index 00000000..c264a7ee --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/agent.py @@ -0,0 +1,505 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import advanced_settings as gcdc_advanced_settings +from google.cloud.dialogflowcx_v3.types import flow +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'SpeechToTextSettings', + 'Agent', + 'ListAgentsRequest', + 'ListAgentsResponse', + 'GetAgentRequest', + 'CreateAgentRequest', + 'UpdateAgentRequest', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'RestoreAgentRequest', + 'ValidateAgentRequest', + 'GetAgentValidationResultRequest', + 'AgentValidationResult', + }, +) + + +class SpeechToTextSettings(proto.Message): + r"""Settings related to speech recognition. + + Attributes: + enable_speech_adaptation (bool): + Whether to use speech adaptation for speech + recognition. + """ + + enable_speech_adaptation = proto.Field( + proto.BOOL, + number=1, + ) + + +class Agent(proto.Message): + r"""Agents are best described as Natural Language Understanding (NLU) + modules that transform user requests into actionable data. You can + include agents in your app, product, or service to determine user + intent and respond to the user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], and so on to + manage the conversation flows.. + + Attributes: + name (str): + The unique identifier of the agent. Required for the + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent] + method. + [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent] + populates the name automatically. Format: + ``projects//locations//agents/``. + display_name (str): + Required. The human-readable name of the + agent, unique within the location. + default_language_code (str): + Required. Immutable. The default language of the agent as a + language tag. See `Language + Support `__ + for a list of the currently supported language codes. This + field cannot be set by the + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent] + method. + supported_language_codes (Sequence[str]): + The list of all languages supported by the agent (except for + the ``default_language_code``). + time_zone (str): + Required. The time zone of the agent from the `time zone + database `__, e.g., + America/New_York, Europe/Paris. + description (str): + The description of the agent. The maximum + length is 500 characters. If exceeded, the + request is rejected. + avatar_uri (str): + The URI of the agent's avatar. Avatars are used throughout + the Dialogflow console and in the self-hosted `Web + Demo `__ + integration. + speech_to_text_settings (google.cloud.dialogflowcx_v3.types.SpeechToTextSettings): + Speech recognition related settings. + start_flow (str): + Immutable. Name of the start flow in this agent. A start + flow will be automatically created when the agent is + created, and can only be deleted by deleting the agent. + Format: + ``projects//locations//agents//flows/``. + security_settings (str): + Name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + reference for the agent. Format: + ``projects//locations//securitySettings/``. + enable_stackdriver_logging (bool): + Indicates if stackdriver logging is enabled for the agent. + Please use + [agent.advanced_settings][google.cloud.dialogflow.cx.v3.AdvancedSettings.LoggingSettings] + instead. + enable_spell_correction (bool): + Indicates if automatic spell correction is + enabled in detect intent requests. + advanced_settings (google.cloud.dialogflowcx_v3.types.AdvancedSettings): + Hierarchical advanced settings for this + agent. The settings exposed at the lower level + overrides the settings exposed at the higher + level. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + default_language_code = proto.Field( + proto.STRING, + number=3, + ) + supported_language_codes = proto.RepeatedField( + proto.STRING, + number=4, + ) + time_zone = proto.Field( + proto.STRING, + number=5, + ) + description = proto.Field( + proto.STRING, + number=6, + ) + avatar_uri = proto.Field( + proto.STRING, + number=7, + ) + speech_to_text_settings = proto.Field( + proto.MESSAGE, + number=13, + message='SpeechToTextSettings', + ) + start_flow = proto.Field( + proto.STRING, + number=16, + ) + security_settings = proto.Field( + proto.STRING, + number=17, + ) + enable_stackdriver_logging = proto.Field( + proto.BOOL, + number=18, + ) + enable_spell_correction = proto.Field( + proto.BOOL, + number=20, + ) + advanced_settings = proto.Field( + proto.MESSAGE, + number=22, + message=gcdc_advanced_settings.AdvancedSettings, + ) + + +class ListAgentsRequest(proto.Message): + r"""The request message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. + + Attributes: + parent (str): + Required. The location to list all agents for. Format: + ``projects//locations/``. + page_size (int): + The maximum number of items to return in a + single page. By default 100 and at most 1000. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAgentsResponse(proto.Message): + r"""The response message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. + + Attributes: + agents (Sequence[google.cloud.dialogflowcx_v3.types.Agent]): + The list of agents. There will be a maximum number of items + returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + agents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Agent', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAgentRequest(proto.Message): + r"""The request message for + [Agents.GetAgent][google.cloud.dialogflow.cx.v3.Agents.GetAgent]. + + Attributes: + name (str): + Required. The name of the agent. Format: + ``projects//locations//agents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAgentRequest(proto.Message): + r"""The request message for + [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent]. + + Attributes: + parent (str): + Required. The location to create a agent for. Format: + ``projects//locations/``. + agent (google.cloud.dialogflowcx_v3.types.Agent): + Required. The agent to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent = proto.Field( + proto.MESSAGE, + number=2, + message='Agent', + ) + + +class UpdateAgentRequest(proto.Message): + r"""The request message for + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent]. + + Attributes: + agent (google.cloud.dialogflowcx_v3.types.Agent): + Required. The agent to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + If the mask is not present, all fields will be + updated. + """ + + agent = proto.Field( + proto.MESSAGE, + number=1, + message='Agent', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteAgentRequest(proto.Message): + r"""The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3.Agents.DeleteAgent]. + + Attributes: + name (str): + Required. The name of the agent to delete. Format: + ``projects//locations//agents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ExportAgentRequest(proto.Message): + r"""The request message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. + + Attributes: + name (str): + Required. The name of the agent to export. Format: + ``projects//locations//agents/``. + agent_uri (str): + Optional. The `Google Cloud + Storage `__ URI to + export the agent to. The format of this URI must be + ``gs:///``. If left unspecified, + the serialized agent is returned inline. + environment (str): + Optional. Environment name. If not set, draft environment is + assumed. Format: + ``projects//locations//agents//environments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + ) + environment = proto.Field( + proto.STRING, + number=5, + ) + + +class ExportAgentResponse(proto.Message): + r"""The response message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. + + Attributes: + agent_uri (str): + The URI to a file containing the exported agent. This field + is populated only if ``agent_uri`` is specified in + [ExportAgentRequest][google.cloud.dialogflow.cx.v3.ExportAgentRequest]. + agent_content (bytes): + Uncompressed raw byte content for agent. + """ + + agent_uri = proto.Field( + proto.STRING, + number=1, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=2, + oneof='agent', + ) + + +class RestoreAgentRequest(proto.Message): + r"""The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3.Agents.RestoreAgent]. + + Attributes: + name (str): + Required. The name of the agent to restore into. Format: + ``projects//locations//agents/``. + agent_uri (str): + The `Google Cloud + Storage `__ URI to + restore agent from. The format of this URI must be + ``gs:///``. + agent_content (bytes): + Uncompressed raw byte content for agent. + restore_option (google.cloud.dialogflowcx_v3.types.RestoreAgentRequest.RestoreOption): + Agent restore mode. If not specified, ``KEEP`` is assumed. + """ + class RestoreOption(proto.Enum): + r"""Restore option.""" + RESTORE_OPTION_UNSPECIFIED = 0 + KEEP = 1 + FALLBACK = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=3, + oneof='agent', + ) + restore_option = proto.Field( + proto.ENUM, + number=5, + enum=RestoreOption, + ) + + +class ValidateAgentRequest(proto.Message): + r"""The request message for + [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3.Agents.ValidateAgent]. + + Attributes: + name (str): + Required. The agent to validate. Format: + ``projects//locations//agents/``. + language_code (str): + If not specified, the agent's default + language is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAgentValidationResultRequest(proto.Message): + r"""The request message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + + Attributes: + name (str): + Required. The agent name. Format: + ``projects//locations//agents//validationResult``. + language_code (str): + If not specified, the agent's default + language is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class AgentValidationResult(proto.Message): + r"""The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + + Attributes: + name (str): + The unique identifier of the agent validation result. + Format: + ``projects//locations//agents//validationResult``. + flow_validation_results (Sequence[google.cloud.dialogflowcx_v3.types.FlowValidationResult]): + Contains all flow validation results. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + flow_validation_results = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=flow.FlowValidationResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/audio_config.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/audio_config.py new file mode 100644 index 00000000..d72ffa87 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/audio_config.py @@ -0,0 +1,359 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'AudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'OutputAudioEncoding', + 'SpeechWordInfo', + 'InputAudioConfig', + 'VoiceSelectionParams', + 'SynthesizeSpeechConfig', + 'OutputAudioConfig', + }, +) + + +class AudioEncoding(proto.Enum): + r"""Audio encoding of the audio content sent in the conversational query + request. Refer to the `Cloud Speech API + documentation `__ + for more details. + """ + AUDIO_ENCODING_UNSPECIFIED = 0 + AUDIO_ENCODING_LINEAR_16 = 1 + AUDIO_ENCODING_FLAC = 2 + AUDIO_ENCODING_MULAW = 3 + AUDIO_ENCODING_AMR = 4 + AUDIO_ENCODING_AMR_WB = 5 + AUDIO_ENCODING_OGG_OPUS = 6 + AUDIO_ENCODING_SPEEX_WITH_HEADER_BYTE = 7 + + +class SpeechModelVariant(proto.Enum): + r"""Variant of the specified [Speech + model][google.cloud.dialogflow.cx.v3.InputAudioConfig.model] to use. + + See the `Cloud Speech + documentation `__ + for which models have different variants. For example, the + "phone_call" model has both a standard and an enhanced variant. When + you use an enhanced model, you will generally receive higher quality + results than for a standard model. + """ + SPEECH_MODEL_VARIANT_UNSPECIFIED = 0 + USE_BEST_AVAILABLE = 1 + USE_STANDARD = 2 + USE_ENHANCED = 3 + + +class SsmlVoiceGender(proto.Enum): + r"""Gender of the voice as described in `SSML voice + element `__. + """ + SSML_VOICE_GENDER_UNSPECIFIED = 0 + SSML_VOICE_GENDER_MALE = 1 + SSML_VOICE_GENDER_FEMALE = 2 + SSML_VOICE_GENDER_NEUTRAL = 3 + + +class OutputAudioEncoding(proto.Enum): + r"""Audio encoding of the output audio format in Text-To-Speech.""" + OUTPUT_AUDIO_ENCODING_UNSPECIFIED = 0 + OUTPUT_AUDIO_ENCODING_LINEAR_16 = 1 + OUTPUT_AUDIO_ENCODING_MP3 = 2 + OUTPUT_AUDIO_ENCODING_MP3_64_KBPS = 4 + OUTPUT_AUDIO_ENCODING_OGG_OPUS = 3 + OUTPUT_AUDIO_ENCODING_MULAW = 5 + + +class SpeechWordInfo(proto.Message): + r"""Information for a word recognized by the speech recognizer. + + Attributes: + word (str): + The word this info is for. + start_offset (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the + audio that corresponds to the start of the + spoken word. This is an experimental feature and + the accuracy of the time offset can vary. + end_offset (google.protobuf.duration_pb2.Duration): + Time offset relative to the beginning of the + audio that corresponds to the end of the spoken + word. This is an experimental feature and the + accuracy of the time offset can vary. + confidence (float): + The Speech confidence between 0.0 and 1.0 for + this word. A higher number indicates an + estimated greater likelihood that the recognized + word is correct. The default of 0.0 is a + sentinel value indicating that confidence was + not set. + + This field is not guaranteed to be fully stable + over time for the same audio input. Users should + also not rely on it to always be provided. + """ + + word = proto.Field( + proto.STRING, + number=3, + ) + start_offset = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + end_offset = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + + +class InputAudioConfig(proto.Message): + r"""Instructs the speech recognizer on how to process the audio + content. + + Attributes: + audio_encoding (google.cloud.dialogflowcx_v3.types.AudioEncoding): + Required. Audio encoding of the audio content + to process. + sample_rate_hertz (int): + Sample rate (in Hertz) of the audio content sent in the + query. Refer to `Cloud Speech API + documentation `__ + for more details. + enable_word_info (bool): + Optional. If ``true``, Dialogflow returns + [SpeechWordInfo][google.cloud.dialogflow.cx.v3.SpeechWordInfo] + in + [StreamingRecognitionResult][google.cloud.dialogflow.cx.v3.StreamingRecognitionResult] + with information about the recognized speech words, e.g. + start and end time offsets. If false or unspecified, Speech + doesn't return any word-level information. + phrase_hints (Sequence[str]): + Optional. A list of strings containing words and phrases + that the speech recognizer should recognize with higher + likelihood. + + See `the Cloud Speech + documentation `__ + for more details. + model (str): + Optional. Which Speech model to select for the given + request. Select the model best suited to your domain to get + best results. If a model is not explicitly specified, then + we auto-select a model based on the parameters in the + InputAudioConfig. If enhanced speech model is enabled for + the agent and an enhanced version of the specified model for + the language does not exist, then the speech is recognized + using the standard version of the specified model. Refer to + `Cloud Speech API + documentation `__ + for more details. + model_variant (google.cloud.dialogflowcx_v3.types.SpeechModelVariant): + Optional. Which variant of the [Speech + model][google.cloud.dialogflow.cx.v3.InputAudioConfig.model] + to use. + single_utterance (bool): + Optional. If ``false`` (default), recognition does not cease + until the client closes the stream. If ``true``, the + recognizer will detect a single spoken utterance in input + audio. Recognition ceases when it detects the audio's voice + has stopped or paused. In this case, once a detected intent + is received, the client should close the stream and start a + new request with a new stream as needed. Note: This setting + is relevant only for streaming methods. + """ + + audio_encoding = proto.Field( + proto.ENUM, + number=1, + enum='AudioEncoding', + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=2, + ) + enable_word_info = proto.Field( + proto.BOOL, + number=13, + ) + phrase_hints = proto.RepeatedField( + proto.STRING, + number=4, + ) + model = proto.Field( + proto.STRING, + number=7, + ) + model_variant = proto.Field( + proto.ENUM, + number=10, + enum='SpeechModelVariant', + ) + single_utterance = proto.Field( + proto.BOOL, + number=8, + ) + + +class VoiceSelectionParams(proto.Message): + r"""Description of which voice to use for speech synthesis. + + Attributes: + name (str): + Optional. The name of the voice. If not set, the service + will choose a voice based on the other parameters such as + language_code and + [ssml_gender][google.cloud.dialogflow.cx.v3.VoiceSelectionParams.ssml_gender]. + + For the list of available voices, please refer to `Supported + voices and + languages `__. + ssml_gender (google.cloud.dialogflowcx_v3.types.SsmlVoiceGender): + Optional. The preferred gender of the voice. If not set, the + service will choose a voice based on the other parameters + such as language_code and + [name][google.cloud.dialogflow.cx.v3.VoiceSelectionParams.name]. + Note that this is only a preference, not requirement. If a + voice of the appropriate gender is not available, the + synthesizer substitutes a voice with a different gender + rather than failing the request. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + ssml_gender = proto.Field( + proto.ENUM, + number=2, + enum='SsmlVoiceGender', + ) + + +class SynthesizeSpeechConfig(proto.Message): + r"""Configuration of how speech should be synthesized. + + Attributes: + speaking_rate (float): + Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 + is the normal native speed supported by the specific voice. + 2.0 is twice as fast, and 0.5 is half as fast. If + unset(0.0), defaults to the native 1.0 speed. Any other + values < 0.25 or > 4.0 will return an error. + pitch (float): + Optional. Speaking pitch, in the range [-20.0, 20.0]. 20 + means increase 20 semitones from the original pitch. -20 + means decrease 20 semitones from the original pitch. + volume_gain_db (float): + Optional. Volume gain (in dB) of the normal native volume + supported by the specific voice, in the range [-96.0, 16.0]. + If unset, or set to a value of 0.0 (dB), will play at normal + native signal amplitude. A value of -6.0 (dB) will play at + approximately half the amplitude of the normal native signal + amplitude. A value of +6.0 (dB) will play at approximately + twice the amplitude of the normal native signal amplitude. + We strongly recommend not to exceed +10 (dB) as there's + usually no effective increase in loudness for any value + greater than that. + effects_profile_id (Sequence[str]): + Optional. An identifier which selects 'audio + effects' profiles that are applied on (post + synthesized) text to speech. Effects are applied + on top of each other in the order they are + given. + voice (google.cloud.dialogflowcx_v3.types.VoiceSelectionParams): + Optional. The desired voice of the + synthesized audio. + """ + + speaking_rate = proto.Field( + proto.DOUBLE, + number=1, + ) + pitch = proto.Field( + proto.DOUBLE, + number=2, + ) + volume_gain_db = proto.Field( + proto.DOUBLE, + number=3, + ) + effects_profile_id = proto.RepeatedField( + proto.STRING, + number=5, + ) + voice = proto.Field( + proto.MESSAGE, + number=4, + message='VoiceSelectionParams', + ) + + +class OutputAudioConfig(proto.Message): + r"""Instructs the speech synthesizer how to generate the output + audio content. + + Attributes: + audio_encoding (google.cloud.dialogflowcx_v3.types.OutputAudioEncoding): + Required. Audio encoding of the synthesized + audio content. + sample_rate_hertz (int): + Optional. The synthesis sample rate (in + hertz) for this audio. If not provided, then the + synthesizer will use the default sample rate + based on the audio encoding. If this is + different from the voice's natural sample rate, + then the synthesizer will honor this request by + converting to the desired sample rate (which + might result in worse audio quality). + synthesize_speech_config (google.cloud.dialogflowcx_v3.types.SynthesizeSpeechConfig): + Optional. Configuration of how speech should + be synthesized. + """ + + audio_encoding = proto.Field( + proto.ENUM, + number=1, + enum='OutputAudioEncoding', + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=2, + ) + synthesize_speech_config = proto.Field( + proto.MESSAGE, + number=3, + message='SynthesizeSpeechConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/deployment.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/deployment.py new file mode 100644 index 00000000..80e910f1 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/deployment.py @@ -0,0 +1,202 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'Deployment', + 'ListDeploymentsRequest', + 'ListDeploymentsResponse', + 'GetDeploymentRequest', + }, +) + + +class Deployment(proto.Message): + r"""Represents an deployment in an environment. A deployment + happens when a flow version configured to be active in the + environment. You can configure running pre-deployment steps, + e.g. running validation test cases, experiment auto-rollout, + etc. + + Attributes: + name (str): + The name of the deployment. + Format: projects//locations//agents//environments//deployments/. + flow_version (str): + The name of the flow version for this + deployment. Format: projects//locations//agents//flows//versions/. + state (google.cloud.dialogflowcx_v3.types.Deployment.State): + The current state of the deployment. + result (google.cloud.dialogflowcx_v3.types.Deployment.Result): + Result of the deployment. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of this deployment. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of this deployment. + """ + class State(proto.Enum): + r"""The state of the deployment.""" + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + + class Result(proto.Message): + r"""Result of the deployment. + + Attributes: + deployment_test_results (Sequence[str]): + Results of test cases running before the deployment. Format: + ``projects//locations//agents//testCases//results/``. + experiment (str): + The name of the experiment triggered by this + deployment. Format: projects//locations//agents//environments//experiments/. + """ + + deployment_test_results = proto.RepeatedField( + proto.STRING, + number=1, + ) + experiment = proto.Field( + proto.STRING, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + flow_version = proto.Field( + proto.STRING, + number=2, + ) + state = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + result = proto.Field( + proto.MESSAGE, + number=4, + message=Result, + ) + start_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class ListDeploymentsRequest(proto.Message): + r"""The request message for + [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3.Deployments.ListDeployments]. + + Attributes: + parent (str): + Required. The + [Environment][google.cloud.dialogflow.cx.v3.Environment] to + list all environments for. Format: + ``projects//locations//agents//environments/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 and at most 100. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDeploymentsResponse(proto.Message): + r"""The response message for + [Deployments.ListDeployments][google.cloud.dialogflow.cx.v3.Deployments.ListDeployments]. + + Attributes: + deployments (Sequence[google.cloud.dialogflowcx_v3.types.Deployment]): + The list of deployments. There will be a maximum number of + items returned based on the page_size field in the request. + The list may in some cases be empty or contain fewer entries + than page_size even if this isn't the last page. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + deployments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Deployment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetDeploymentRequest(proto.Message): + r"""The request message for + [Deployments.GetDeployment][google.cloud.dialogflow.cx.v3.Deployments.GetDeployment]. + + Attributes: + name (str): + Required. The name of the + [Deployment][google.cloud.dialogflow.cx.v3.Deployment]. + Format: + ``projects//locations//agents//environments//deployments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/entity_type.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/entity_type.py new file mode 100644 index 00000000..86f31202 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/entity_type.py @@ -0,0 +1,427 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'EntityType', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'GetEntityTypeRequest', + 'CreateEntityTypeRequest', + 'UpdateEntityTypeRequest', + 'DeleteEntityTypeRequest', + }, +) + + +class EntityType(proto.Message): + r"""Entities are extracted from user input and represent parameters that + are meaningful to your application. For example, a date range, a + proper name such as a geographic location or landmark, and so on. + Entities represent actionable data for your application. + + When you define an entity, you can also include synonyms that all + map to that entity. For example, "soft drink", "soda", "pop", and so + on. + + There are three types of entities: + + - **System** - entities that are defined by the Dialogflow API for + common data types such as date, time, currency, and so on. A + system entity is represented by the ``EntityType`` type. + + - **Custom** - entities that are defined by you that represent + actionable data that is meaningful to your application. For + example, you could define a ``pizza.sauce`` entity for red or + white pizza sauce, a ``pizza.cheese`` entity for the different + types of cheese on a pizza, a ``pizza.topping`` entity for + different toppings, and so on. A custom entity is represented by + the ``EntityType`` type. + + - **User** - entities that are built for an individual user such as + favorites, preferences, playlists, and so on. A user entity is + represented by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the `Dialogflow + documentation `__. + + Attributes: + name (str): + The unique identifier of the entity type. Required for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.UpdateEntityType]. + Format: + ``projects//locations//agents//entityTypes/``. + display_name (str): + Required. The human-readable name of the + entity type, unique within the agent. + kind (google.cloud.dialogflowcx_v3.types.EntityType.Kind): + Required. Indicates the kind of entity type. + auto_expansion_mode (google.cloud.dialogflowcx_v3.types.EntityType.AutoExpansionMode): + Indicates whether the entity type can be + automatically expanded. + entities (Sequence[google.cloud.dialogflowcx_v3.types.EntityType.Entity]): + The collection of entity entries associated + with the entity type. + excluded_phrases (Sequence[google.cloud.dialogflowcx_v3.types.EntityType.ExcludedPhrase]): + Collection of exceptional words and phrases that shouldn't + be matched. For example, if you have a size entity type with + entry ``giant``\ (an adjective), you might consider adding + ``giants``\ (a noun) as an exclusion. If the kind of entity + type is ``KIND_MAP``, then the phrases specified by entities + and excluded phrases should be mutually exclusive. + enable_fuzzy_extraction (bool): + Enables fuzzy entity extraction during + classification. + redact (bool): + Indicates whether parameters of the entity + type should be redacted in log. If redaction is + enabled, page parameters and intent parameters + referring to the entity type will be replaced by + parameter name when logging. + """ + class Kind(proto.Enum): + r"""Represents kinds of entities.""" + KIND_UNSPECIFIED = 0 + KIND_MAP = 1 + KIND_LIST = 2 + KIND_REGEXP = 3 + + class AutoExpansionMode(proto.Enum): + r"""Represents different entity type expansion modes. Automated + expansion allows an agent to recognize values that have not been + explicitly listed in the entity (for example, new kinds of + shopping list items). + """ + AUTO_EXPANSION_MODE_UNSPECIFIED = 0 + AUTO_EXPANSION_MODE_DEFAULT = 1 + + class Entity(proto.Message): + r"""An **entity entry** for an associated entity type. + + Attributes: + value (str): + Required. The primary value associated with this entity + entry. For example, if the entity type is *vegetable*, the + value could be *scallions*. + + For ``KIND_MAP`` entity types: + + - A canonical value to be used in place of synonyms. + + For ``KIND_LIST`` entity types: + + - A string that can contain references to other entity + types (with or without aliases). + synonyms (Sequence[str]): + Required. A collection of value synonyms. For example, if + the entity type is *vegetable*, and ``value`` is + *scallions*, a synonym could be *green onions*. + + For ``KIND_LIST`` entity types: + + - This collection must contain exactly one synonym equal to + ``value``. + """ + + value = proto.Field( + proto.STRING, + number=1, + ) + synonyms = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class ExcludedPhrase(proto.Message): + r"""An excluded entity phrase that should not be matched. + + Attributes: + value (str): + Required. The word or phrase to be excluded. + """ + + value = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + kind = proto.Field( + proto.ENUM, + number=3, + enum=Kind, + ) + auto_expansion_mode = proto.Field( + proto.ENUM, + number=4, + enum=AutoExpansionMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Entity, + ) + excluded_phrases = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=ExcludedPhrase, + ) + enable_fuzzy_extraction = proto.Field( + proto.BOOL, + number=7, + ) + redact = proto.Field( + proto.BOOL, + number=9, + ) + + +class ListEntityTypesRequest(proto.Message): + r"""The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. + + Attributes: + parent (str): + Required. The agent to list all entity types for. Format: + ``projects//locations//agents/``. + language_code (str): + The language to list entity types for. The following fields + are language dependent: + + - ``EntityType.entities.value`` + - ``EntityType.entities.synonyms`` + - ``EntityType.excluded_phrases.value`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + page_size (int): + The maximum number of items to return in a + single page. By default 100 and at most 1000. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListEntityTypesResponse(proto.Message): + r"""The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. + + Attributes: + entity_types (Sequence[google.cloud.dialogflowcx_v3.types.EntityType]): + The list of entity types. There will be a maximum number of + items returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + entity_types = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EntityType', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEntityTypeRequest(proto.Message): + r"""The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.GetEntityType]. + + Attributes: + name (str): + Required. The name of the entity type. Format: + ``projects//locations//agents//entityTypes/``. + language_code (str): + The language to retrieve the entity type for. The following + fields are language dependent: + + - ``EntityType.entities.value`` + - ``EntityType.entities.synonyms`` + - ``EntityType.excluded_phrases.value`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateEntityTypeRequest(proto.Message): + r"""The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.CreateEntityType]. + + Attributes: + parent (str): + Required. The agent to create a entity type for. Format: + ``projects//locations//agents/``. + entity_type (google.cloud.dialogflowcx_v3.types.EntityType): + Required. The entity type to create. + language_code (str): + The language of the following fields in ``entity_type``: + + - ``EntityType.entities.value`` + - ``EntityType.entities.synonyms`` + - ``EntityType.excluded_phrases.value`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.MESSAGE, + number=2, + message='EntityType', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateEntityTypeRequest(proto.Message): + r"""The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.UpdateEntityType]. + + Attributes: + entity_type (google.cloud.dialogflowcx_v3.types.EntityType): + Required. The entity type to update. + language_code (str): + The language of the following fields in ``entity_type``: + + - ``EntityType.entities.value`` + - ``EntityType.entities.synonyms`` + - ``EntityType.excluded_phrases.value`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + """ + + entity_type = proto.Field( + proto.MESSAGE, + number=1, + message='EntityType', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEntityTypeRequest(proto.Message): + r"""The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.DeleteEntityType]. + + Attributes: + name (str): + Required. The name of the entity type to delete. Format: + ``projects//locations//agents//entityTypes/``. + force (bool): + This field has no effect for entity type not being used. For + entity types that are used by intents or pages: + + - If ``force`` is set to false, an error will be returned + with message indicating the referencing resources. + - If ``force`` is set to true, Dialogflow will remove the + entity type, as well as any references to the entity type + (i.e. Page + [parameter][google.cloud.dialogflow.cx.v3.Form.Parameter] + of the entity type will be changed to '@sys.any' and + intent + [parameter][google.cloud.dialogflow.cx.v3.Intent.Parameter] + of the entity type will be removed). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/environment.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/environment.py new file mode 100644 index 00000000..71fb901b --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/environment.py @@ -0,0 +1,587 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import test_case +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'Environment', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'GetEnvironmentRequest', + 'CreateEnvironmentRequest', + 'UpdateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'LookupEnvironmentHistoryRequest', + 'LookupEnvironmentHistoryResponse', + 'ContinuousTestResult', + 'RunContinuousTestRequest', + 'RunContinuousTestResponse', + 'RunContinuousTestMetadata', + 'ListContinuousTestResultsRequest', + 'ListContinuousTestResultsResponse', + 'DeployFlowRequest', + 'DeployFlowResponse', + 'DeployFlowMetadata', + }, +) + + +class Environment(proto.Message): + r"""Represents an environment for an agent. You can create + multiple versions of your agent and publish them to separate + environments. When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as an agent + version, which is an immutable snapshot of your agent. When you + save the draft agent, it is published to the default + environment. When you create agent versions, you can publish + them to custom environments. You can create a variety of custom + environments for testing, development, production, etc. + + Attributes: + name (str): + The name of the environment. Format: + ``projects//locations//agents//environments/``. + display_name (str): + Required. The human-readable name of the + environment (unique in an agent). Limit of 64 + characters. + description (str): + The human-readable description of the + environment. The maximum length is 500 + characters. If exceeded, the request is + rejected. + version_configs (Sequence[google.cloud.dialogflowcx_v3.types.Environment.VersionConfig]): + Required. A list of configurations for flow versions. You + should include version configs for all flows that are + reachable from [``Start Flow``][Agent.start_flow] in the + agent. Otherwise, an error will be returned. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time of this environment. + test_cases_config (google.cloud.dialogflowcx_v3.types.Environment.TestCasesConfig): + The test cases config for continuous tests of + this environment. + """ + + class VersionConfig(proto.Message): + r"""Configuration for the version. + + Attributes: + version (str): + Required. Format: projects//locations//agents//flows//versions/. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + + class TestCasesConfig(proto.Message): + r"""The configuration for continuous tests. + + Attributes: + test_cases (Sequence[str]): + A list of test case names to run. They should be under the + same agent. Format of each test case name: + ``projects//locations/ /agents//testCases/`` + enable_continuous_run (bool): + Whether to run test cases in + [TestCasesConfig.test_cases][google.cloud.dialogflow.cx.v3.Environment.TestCasesConfig.test_cases] + periodically. Default false. If set to ture, run once a day. + enable_predeployment_run (bool): + Whether to run test cases in + [TestCasesConfig.test_cases][google.cloud.dialogflow.cx.v3.Environment.TestCasesConfig.test_cases] + before deploying a flow version to the environment. Default + false. + """ + + test_cases = proto.RepeatedField( + proto.STRING, + number=1, + ) + enable_continuous_run = proto.Field( + proto.BOOL, + number=2, + ) + enable_predeployment_run = proto.Field( + proto.BOOL, + number=3, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + version_configs = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=VersionConfig, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + test_cases_config = proto.Field( + proto.MESSAGE, + number=7, + message=TestCasesConfig, + ) + + +class ListEnvironmentsRequest(proto.Message): + r"""The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. + + Attributes: + parent (str): + Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] + to list all environments for. Format: + ``projects//locations//agents/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 and at most 100. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEnvironmentsResponse(proto.Message): + r"""The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. + + Attributes: + environments (Sequence[google.cloud.dialogflowcx_v3.types.Environment]): + The list of environments. There will be a maximum number of + items returned based on the page_size field in the request. + The list may in some cases be empty or contain fewer entries + than page_size even if this isn't the last page. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + environments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Environment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3.Environments.GetEnvironment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3.Environments.CreateEnvironment]. + + Attributes: + parent (str): + Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] + to create an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents/``. + environment (google.cloud.dialogflowcx_v3.types.Environment): + Required. The environment to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.MESSAGE, + number=2, + message='Environment', + ) + + +class UpdateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3.Environments.UpdateEnvironment]. + + Attributes: + environment (google.cloud.dialogflowcx_v3.types.Environment): + Required. The environment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + environment = proto.Field( + proto.MESSAGE, + number=1, + message='Environment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3.Environments.DeleteEnvironment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] to + delete. Format: + ``projects//locations//agents//environments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class LookupEnvironmentHistoryRequest(proto.Message): + r"""The request message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. + + Attributes: + name (str): + Required. Resource name of the environment to look up the + history for. Format: + ``projects//locations//agents//environments/``. + page_size (int): + The maximum number of items to return in a + single page. By default 100 and at most 1000. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class LookupEnvironmentHistoryResponse(proto.Message): + r"""The response message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. + + Attributes: + environments (Sequence[google.cloud.dialogflowcx_v3.types.Environment]): + Represents a list of snapshots for an environment. Time of + the snapshots is stored in + [``update_time``][google.cloud.dialogflow.cx.v3.Environment.update_time]. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + environments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Environment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ContinuousTestResult(proto.Message): + r"""Represents a result from running a test case in an agent + environment. + + Attributes: + name (str): + The resource name for the continuous test result. Format: + ``projects//locations//agents//environments//continuousTestResults/``. + result (google.cloud.dialogflowcx_v3.types.ContinuousTestResult.AggregatedTestResult): + The result of this continuous test run, i.e. + whether all the tests in this continuous test + run pass or not. + test_case_results (Sequence[str]): + A list of individual test case results names + in this continuous test run. + run_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the continuous testing run starts. + """ + class AggregatedTestResult(proto.Enum): + r"""The overall result for a continuous test run in an agent + environment. + """ + AGGREGATED_TEST_RESULT_UNSPECIFIED = 0 + PASSED = 1 + FAILED = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + result = proto.Field( + proto.ENUM, + number=2, + enum=AggregatedTestResult, + ) + test_case_results = proto.RepeatedField( + proto.STRING, + number=3, + ) + run_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class RunContinuousTestRequest(proto.Message): + r"""The request message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3.Environments.RunContinuousTest]. + + Attributes: + environment (str): + Required. Format: + ``projects//locations//agents//environments/``. + """ + + environment = proto.Field( + proto.STRING, + number=1, + ) + + +class RunContinuousTestResponse(proto.Message): + r"""The response message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3.Environments.RunContinuousTest]. + + Attributes: + continuous_test_result (google.cloud.dialogflowcx_v3.types.ContinuousTestResult): + The result for a continuous test run. + """ + + continuous_test_result = proto.Field( + proto.MESSAGE, + number=1, + message='ContinuousTestResult', + ) + + +class RunContinuousTestMetadata(proto.Message): + r"""Metadata returned for the + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3.Environments.RunContinuousTest] + long running operation. + + Attributes: + errors (Sequence[google.cloud.dialogflowcx_v3.types.TestError]): + The test errors. + """ + + errors = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=test_case.TestError, + ) + + +class ListContinuousTestResultsRequest(proto.Message): + r"""The request message for + [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3.Environments.ListContinuousTestResults]. + + Attributes: + parent (str): + Required. The environment to list results for. Format: + ``projects//locations//agents// environments/``. + page_size (int): + The maximum number of items to return in a + single page. By default 100 and at most 1000. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListContinuousTestResultsResponse(proto.Message): + r"""The response message for [Environments.ListTestCaseResults][]. + + Attributes: + continuous_test_results (Sequence[google.cloud.dialogflowcx_v3.types.ContinuousTestResult]): + The list of continuous test results. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + continuous_test_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ContinuousTestResult', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class DeployFlowRequest(proto.Message): + r"""The request message for + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3.Environments.DeployFlow]. + + Attributes: + environment (str): + Required. The environment to deploy the flow to. Format: + ``projects//locations//agents// environments/``. + flow_version (str): + Required. The flow version to deploy. Format: + ``projects//locations//agents// flows//versions/``. + """ + + environment = proto.Field( + proto.STRING, + number=1, + ) + flow_version = proto.Field( + proto.STRING, + number=2, + ) + + +class DeployFlowResponse(proto.Message): + r"""The response message for + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3.Environments.DeployFlow]. + + Attributes: + environment (google.cloud.dialogflowcx_v3.types.Environment): + The updated environment where the flow is + deployed. + deployment (str): + The name of the flow version + [Deployment][google.cloud.dialogflow.cx.v3.Deployment]. + Format: + ``projects//locations//agents// environments//deployments/``. + """ + + environment = proto.Field( + proto.MESSAGE, + number=1, + message='Environment', + ) + deployment = proto.Field( + proto.STRING, + number=2, + ) + + +class DeployFlowMetadata(proto.Message): + r"""Metadata returned for the + [Environments.DeployFlow][google.cloud.dialogflow.cx.v3.Environments.DeployFlow] + long running operation. + + Attributes: + test_errors (Sequence[google.cloud.dialogflowcx_v3.types.TestError]): + Errors of running deployment tests. + """ + + test_errors = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=test_case.TestError, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/experiment.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/experiment.py new file mode 100644 index 00000000..645bda49 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/experiment.py @@ -0,0 +1,703 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'Experiment', + 'VersionVariants', + 'VariantsHistory', + 'RolloutConfig', + 'RolloutState', + 'ListExperimentsRequest', + 'ListExperimentsResponse', + 'GetExperimentRequest', + 'CreateExperimentRequest', + 'UpdateExperimentRequest', + 'DeleteExperimentRequest', + 'StartExperimentRequest', + 'StopExperimentRequest', + }, +) + + +class Experiment(proto.Message): + r"""Represents an experiment in an environment. + + Attributes: + name (str): + The name of the experiment. + Format: projects//locations//agents//environments//experiments/.. + display_name (str): + Required. The human-readable name of the + experiment (unique in an environment). Limit of + 64 characters. + description (str): + The human-readable description of the + experiment. + state (google.cloud.dialogflowcx_v3.types.Experiment.State): + The current state of the experiment. + Transition triggered by + Experiments.StartExperiment: DRAFT->RUNNING. + Transition triggered by + Experiments.CancelExperiment: DRAFT->DONE or + RUNNING->DONE. + definition (google.cloud.dialogflowcx_v3.types.Experiment.Definition): + The definition of the experiment. + rollout_config (google.cloud.dialogflowcx_v3.types.RolloutConfig): + The configuration for auto rollout. If set, + there should be exactly two variants in the + experiment (control variant being the default + version of the flow), the traffic allocation for + the non-control variant will gradually increase + to 100% when conditions are met, and eventually + replace the control variant to become the + default version of the flow. + rollout_state (google.cloud.dialogflowcx_v3.types.RolloutState): + State of the auto rollout process. + rollout_failure_reason (str): + The reason why rollout has failed. Should only be set when + state is ROLLOUT_FAILED. + result (google.cloud.dialogflowcx_v3.types.Experiment.Result): + Inference result of the experiment. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Creation time of this experiment. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of this experiment. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of this experiment. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Last update time of this experiment. + experiment_length (google.protobuf.duration_pb2.Duration): + Maximum number of days to run the + experiment/rollout. If auto-rollout is not + enabled, default value and maximum will be 30 + days. If auto-rollout is enabled, default value + and maximum will be 6 days. + variants_history (Sequence[google.cloud.dialogflowcx_v3.types.VariantsHistory]): + The history of updates to the experiment + variants. + """ + class State(proto.Enum): + r"""The state of the experiment.""" + STATE_UNSPECIFIED = 0 + DRAFT = 1 + RUNNING = 2 + DONE = 3 + ROLLOUT_FAILED = 4 + + class Definition(proto.Message): + r"""Definition of the experiment. + + Attributes: + condition (str): + The condition defines which subset of sessions are selected + for this experiment. If not specified, all sessions are + eligible. E.g. "query_input.language_code=en" See the + `conditions + reference `__. + version_variants (google.cloud.dialogflowcx_v3.types.VersionVariants): + The flow versions as the variants of this + experiment. + """ + + condition = proto.Field( + proto.STRING, + number=1, + ) + version_variants = proto.Field( + proto.MESSAGE, + number=2, + oneof='variants', + message='VersionVariants', + ) + + class Result(proto.Message): + r"""The inference result which includes an objective metric to + optimize and the confidence interval. + + Attributes: + version_metrics (Sequence[google.cloud.dialogflowcx_v3.types.Experiment.Result.VersionMetrics]): + Version variants and metrics. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + The last time the experiment's stats data was + updated. Will have default value if stats have + never been computed for this experiment. + """ + class MetricType(proto.Enum): + r"""Types of ratio-based metric for Dialogflow experiment.""" + METRIC_UNSPECIFIED = 0 + CONTAINED_SESSION_NO_CALLBACK_RATE = 1 + LIVE_AGENT_HANDOFF_RATE = 2 + CALLBACK_SESSION_RATE = 3 + ABANDONED_SESSION_RATE = 4 + SESSION_END_RATE = 5 + + class CountType(proto.Enum): + r"""Types of count-based metric for Dialogflow experiment.""" + COUNT_TYPE_UNSPECIFIED = 0 + TOTAL_NO_MATCH_COUNT = 1 + TOTAL_TURN_COUNT = 2 + AVERAGE_TURN_COUNT = 3 + + class ConfidenceInterval(proto.Message): + r"""A confidence interval is a range of possible values for the + experiment objective you are trying to measure. + + Attributes: + confidence_level (float): + The confidence level used to construct the + interval, i.e. there is X% chance that the true + value is within this interval. + ratio (float): + The percent change between an experiment + metric's value and the value for its control. + lower_bound (float): + Lower bound of the interval. + upper_bound (float): + Upper bound of the interval. + """ + + confidence_level = proto.Field( + proto.DOUBLE, + number=1, + ) + ratio = proto.Field( + proto.DOUBLE, + number=2, + ) + lower_bound = proto.Field( + proto.DOUBLE, + number=3, + ) + upper_bound = proto.Field( + proto.DOUBLE, + number=4, + ) + + class Metric(proto.Message): + r"""Metric and corresponding confidence intervals. + + Attributes: + type_ (google.cloud.dialogflowcx_v3.types.Experiment.Result.MetricType): + Ratio-based metric type. Only one of type or count_type is + specified in each Metric. + count_type (google.cloud.dialogflowcx_v3.types.Experiment.Result.CountType): + Count-based metric type. Only one of type or count_type is + specified in each Metric. + ratio (float): + Ratio value of a metric. + count (float): + Count value of a metric. + confidence_interval (google.cloud.dialogflowcx_v3.types.Experiment.Result.ConfidenceInterval): + The probability that the treatment is better + than all other treatments in the experiment + """ + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='Experiment.Result.MetricType', + ) + count_type = proto.Field( + proto.ENUM, + number=5, + enum='Experiment.Result.CountType', + ) + ratio = proto.Field( + proto.DOUBLE, + number=2, + oneof='value', + ) + count = proto.Field( + proto.DOUBLE, + number=4, + oneof='value', + ) + confidence_interval = proto.Field( + proto.MESSAGE, + number=3, + message='Experiment.Result.ConfidenceInterval', + ) + + class VersionMetrics(proto.Message): + r"""Version variant and associated metrics. + + Attributes: + version (str): + The name of the flow + [Version][google.cloud.dialogflow.cx.v3.Version]. Format: + ``projects//locations//agents//flows//versions/``. + metrics (Sequence[google.cloud.dialogflowcx_v3.types.Experiment.Result.Metric]): + The metrics and corresponding confidence + intervals in the inference result. + session_count (int): + Number of sessions that were allocated to + this version. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + metrics = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Experiment.Result.Metric', + ) + session_count = proto.Field( + proto.INT32, + number=3, + ) + + version_metrics = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Experiment.Result.VersionMetrics', + ) + last_update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + definition = proto.Field( + proto.MESSAGE, + number=5, + message=Definition, + ) + rollout_config = proto.Field( + proto.MESSAGE, + number=14, + message='RolloutConfig', + ) + rollout_state = proto.Field( + proto.MESSAGE, + number=15, + message='RolloutState', + ) + rollout_failure_reason = proto.Field( + proto.STRING, + number=16, + ) + result = proto.Field( + proto.MESSAGE, + number=6, + message=Result, + ) + create_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + start_time = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + last_update_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + experiment_length = proto.Field( + proto.MESSAGE, + number=11, + message=duration_pb2.Duration, + ) + variants_history = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='VariantsHistory', + ) + + +class VersionVariants(proto.Message): + r"""A list of flow version variants. + + Attributes: + variants (Sequence[google.cloud.dialogflowcx_v3.types.VersionVariants.Variant]): + A list of flow version variants. + """ + + class Variant(proto.Message): + r"""A single flow version with specified traffic allocation. + + Attributes: + version (str): + The name of the flow version. Format: + ``projects//locations//agents//flows//versions/``. + traffic_allocation (float): + Percentage of the traffic which should be + routed to this version of flow. Traffic + allocation for a single flow must sum up to 1.0. + is_control_group (bool): + Whether the variant is for the control group. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + traffic_allocation = proto.Field( + proto.FLOAT, + number=2, + ) + is_control_group = proto.Field( + proto.BOOL, + number=3, + ) + + variants = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Variant, + ) + + +class VariantsHistory(proto.Message): + r"""The history of variants update. + + Attributes: + version_variants (google.cloud.dialogflowcx_v3.types.VersionVariants): + The flow versions as the variants. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Update time of the variants. + """ + + version_variants = proto.Field( + proto.MESSAGE, + number=1, + oneof='variants', + message='VersionVariants', + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class RolloutConfig(proto.Message): + r"""The configuration for auto rollout. + + Attributes: + rollout_steps (Sequence[google.cloud.dialogflowcx_v3.types.RolloutConfig.RolloutStep]): + Steps to roll out a flow version. Steps + should be sorted by percentage in ascending + order. + rollout_condition (str): + The conditions that are used to evaluate the success of a + rollout step. If not specified, all rollout steps will + proceed to the next one unless failure conditions are met. + E.g. "containment_rate > 60% AND callback_rate < 20%". See + the `conditions + reference `__. + failure_condition (str): + The conditions that are used to evaluate the failure of a + rollout step. If not specified, no rollout steps will fail. + E.g. "containment_rate < 10% OR average_turn_count < 3". See + the `conditions + reference `__. + """ + + class RolloutStep(proto.Message): + r"""A single rollout step with specified traffic allocation. + + Attributes: + display_name (str): + The name of the rollout step; + traffic_percent (int): + The percentage of traffic allocated to the flow version of + this rollout step. (0%, 100%]. + min_duration (google.protobuf.duration_pb2.Duration): + The minimum time that this step should last. + Should be longer than 1 hour. If not set, the + default minimum duration for each step will be 1 + hour. + """ + + display_name = proto.Field( + proto.STRING, + number=1, + ) + traffic_percent = proto.Field( + proto.INT32, + number=2, + ) + min_duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + rollout_steps = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=RolloutStep, + ) + rollout_condition = proto.Field( + proto.STRING, + number=2, + ) + failure_condition = proto.Field( + proto.STRING, + number=3, + ) + + +class RolloutState(proto.Message): + r"""State of the auto-rollout process. + + Attributes: + step (str): + Display name of the current auto rollout + step. + step_index (int): + Index of the current step in the auto rollout + steps list. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of the current step. + """ + + step = proto.Field( + proto.STRING, + number=1, + ) + step_index = proto.Field( + proto.INT32, + number=3, + ) + start_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ListExperimentsRequest(proto.Message): + r"""The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + + Attributes: + parent (str): + Required. The + [Environment][google.cloud.dialogflow.cx.v3.Environment] to + list all environments for. Format: + ``projects//locations//agents//environments/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 and at most 100. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListExperimentsResponse(proto.Message): + r"""The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + + Attributes: + experiments (Sequence[google.cloud.dialogflowcx_v3.types.Experiment]): + The list of experiments. There will be a maximum number of + items returned based on the page_size field in the request. + The list may in some cases be empty or contain fewer entries + than page_size even if this isn't the last page. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + experiments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Experiment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetExperimentRequest(proto.Message): + r"""The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateExperimentRequest(proto.Message): + r"""The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. + + Attributes: + parent (str): + Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] + to create an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents//environments/``. + experiment (google.cloud.dialogflowcx_v3.types.Experiment): + Required. The experiment to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + experiment = proto.Field( + proto.MESSAGE, + number=2, + message='Experiment', + ) + + +class UpdateExperimentRequest(proto.Message): + r"""The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. + + Attributes: + experiment (google.cloud.dialogflowcx_v3.types.Experiment): + Required. The experiment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + experiment = proto.Field( + proto.MESSAGE, + number=1, + message='Experiment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteExperimentRequest(proto.Message): + r"""The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] to + delete. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class StartExperimentRequest(proto.Message): + r"""The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. + + Attributes: + name (str): + Required. Resource name of the experiment to start. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class StopExperimentRequest(proto.Message): + r"""The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. + + Attributes: + name (str): + Required. Resource name of the experiment to stop. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/flow.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/flow.py new file mode 100644 index 00000000..825fae24 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/flow.py @@ -0,0 +1,642 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import validation_message +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'NluSettings', + 'Flow', + 'CreateFlowRequest', + 'DeleteFlowRequest', + 'ListFlowsRequest', + 'ListFlowsResponse', + 'GetFlowRequest', + 'UpdateFlowRequest', + 'TrainFlowRequest', + 'ValidateFlowRequest', + 'GetFlowValidationResultRequest', + 'FlowValidationResult', + 'ImportFlowRequest', + 'ImportFlowResponse', + 'ExportFlowRequest', + 'ExportFlowResponse', + }, +) + + +class NluSettings(proto.Message): + r"""Settings related to NLU. + + Attributes: + model_type (google.cloud.dialogflowcx_v3.types.NluSettings.ModelType): + Indicates the type of NLU model. + classification_threshold (float): + To filter out false positive results and + still get variety in matched natural language + inputs for your agent, you can tune the machine + learning classification threshold. If the + returned score value is less than the threshold + value, then a no-match event will be triggered. + The score values range from 0.0 (completely + uncertain) to 1.0 (completely certain). If set + to 0.0, the default of 0.3 is used. + model_training_mode (google.cloud.dialogflowcx_v3.types.NluSettings.ModelTrainingMode): + Indicates NLU model training mode. + """ + class ModelType(proto.Enum): + r"""NLU model type.""" + MODEL_TYPE_UNSPECIFIED = 0 + MODEL_TYPE_STANDARD = 1 + MODEL_TYPE_ADVANCED = 3 + + class ModelTrainingMode(proto.Enum): + r"""NLU model training mode.""" + MODEL_TRAINING_MODE_UNSPECIFIED = 0 + MODEL_TRAINING_MODE_AUTOMATIC = 1 + MODEL_TRAINING_MODE_MANUAL = 2 + + model_type = proto.Field( + proto.ENUM, + number=1, + enum=ModelType, + ) + classification_threshold = proto.Field( + proto.FLOAT, + number=3, + ) + model_training_mode = proto.Field( + proto.ENUM, + number=4, + enum=ModelTrainingMode, + ) + + +class Flow(proto.Message): + r"""Flows represents the conversation flows when you build your + chatbot agent. + A flow consists of many pages connected by the transition + routes. Conversations always start with the built-in Start Flow + (with an all-0 ID). Transition routes can direct the + conversation session from the current flow (parent flow) to + another flow (sub flow). When the sub flow is finished, + Dialogflow will bring the session back to the parent flow, where + the sub flow is started. + + Usually, when a transition route is followed by a matched + intent, the intent will be "consumed". This means the intent + won't activate more transition routes. However, when the + followed transition route moves the conversation session into a + different flow, the matched intent can be carried over and to be + consumed in the target flow. + + Attributes: + name (str): + The unique identifier of the flow. Format: + ``projects//locations//agents//flows/``. + display_name (str): + Required. The human-readable name of the + flow. + description (str): + The description of the flow. The maximum + length is 500 characters. If exceeded, the + request is rejected. + transition_routes (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRoute]): + A flow's transition routes serve two purposes: + + - They are responsible for matching the user's first + utterances in the flow. + - They are inherited by every page's [transition + routes][Page.transition_routes] and can support use cases + such as the user saying "help" or "can I talk to a + human?", which can be handled in a common way regardless + of the current page. Transition routes defined in the + page have higher priority than those defined in the flow. + + TransitionRoutes are evalauted in the following order: + + - TransitionRoutes with intent specified.. + - TransitionRoutes with only condition specified. + + TransitionRoutes with intent specified are inherited by + pages in the flow. + event_handlers (Sequence[google.cloud.dialogflowcx_v3.types.EventHandler]): + A flow's event handlers serve two purposes: + + - They are responsible for handling events (e.g. no match, + webhook errors) in the flow. + - They are inherited by every page's [event + handlers][Page.event_handlers], which can be used to + handle common events regardless of the current page. + Event handlers defined in the page have higher priority + than those defined in the flow. + + Unlike + [transition_routes][google.cloud.dialogflow.cx.v3.Flow.transition_routes], + these handlers are evaluated on a first-match basis. The + first one that matches the event get executed, with the rest + being ignored. + transition_route_groups (Sequence[str]): + A flow's transition route group serve two purposes: + + - They are responsible for matching the user's first + utterances in the flow. + - They are inherited by every page's [transition route + groups][Page.transition_route_groups]. Transition route + groups defined in the page have higher priority than + those defined in the flow. + + Format:\ ``projects//locations//agents//flows//transitionRouteGroups/``. + nlu_settings (google.cloud.dialogflowcx_v3.types.NluSettings): + NLU related settings of the flow. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + transition_routes = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=page.TransitionRoute, + ) + event_handlers = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=page.EventHandler, + ) + transition_route_groups = proto.RepeatedField( + proto.STRING, + number=15, + ) + nlu_settings = proto.Field( + proto.MESSAGE, + number=11, + message='NluSettings', + ) + + +class CreateFlowRequest(proto.Message): + r"""The request message for + [Flows.CreateFlow][google.cloud.dialogflow.cx.v3.Flows.CreateFlow]. + + Attributes: + parent (str): + Required. The agent to create a flow for. Format: + ``projects//locations//agents/``. + flow (google.cloud.dialogflowcx_v3.types.Flow): + Required. The flow to create. + language_code (str): + The language of the following fields in ``flow``: + + - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + flow = proto.Field( + proto.MESSAGE, + number=2, + message='Flow', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteFlowRequest(proto.Message): + r"""The request message for + [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3.Flows.DeleteFlow]. + + Attributes: + name (str): + Required. The name of the flow to delete. Format: + ``projects//locations//agents//flows/``. + force (bool): + This field has no effect for flows with no incoming + transitions. For flows with incoming transitions: + + - If ``force`` is set to false, an error will be returned + with message indicating the incoming transitions. + - If ``force`` is set to true, Dialogflow will remove the + flow, as well as any transitions to the flow (i.e. + [Target flow][EventHandler.target_flow] in event handlers + or [Target flow][TransitionRoute.target_flow] in + transition routes that point to this flow will be + cleared). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class ListFlowsRequest(proto.Message): + r"""The request message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. + + Attributes: + parent (str): + Required. The agent containing the flows. Format: + ``projects//locations//agents/``. + page_size (int): + The maximum number of items to return in a + single page. By default 100 and at most 1000. + page_token (str): + The next_page_token value returned from a previous list + request. + language_code (str): + The language to list flows for. The following fields are + language dependent: + + - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class ListFlowsResponse(proto.Message): + r"""The response message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. + + Attributes: + flows (Sequence[google.cloud.dialogflowcx_v3.types.Flow]): + The list of flows. There will be a maximum number of items + returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + flows = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Flow', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFlowRequest(proto.Message): + r"""The response message for + [Flows.GetFlow][google.cloud.dialogflow.cx.v3.Flows.GetFlow]. + + Attributes: + name (str): + Required. The name of the flow to get. Format: + ``projects//locations//agents//flows/``. + language_code (str): + The language to retrieve the flow for. The following fields + are language dependent: + + - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateFlowRequest(proto.Message): + r"""The request message for + [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3.Flows.UpdateFlow]. + + Attributes: + flow (google.cloud.dialogflowcx_v3.types.Flow): + Required. The flow to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + If the mask is not present, all fields will be + updated. + language_code (str): + The language of the following fields in ``flow``: + + - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + flow = proto.Field( + proto.MESSAGE, + number=1, + message='Flow', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class TrainFlowRequest(proto.Message): + r"""The request message for + [Flows.TrainFlow][google.cloud.dialogflow.cx.v3.Flows.TrainFlow]. + + Attributes: + name (str): + Required. The flow to train. Format: + ``projects//locations//agents//flows/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ValidateFlowRequest(proto.Message): + r"""The request message for + [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3.Flows.ValidateFlow]. + + Attributes: + name (str): + Required. The flow to validate. Format: + ``projects//locations//agents//flows/``. + language_code (str): + If not specified, the agent's default + language is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFlowValidationResultRequest(proto.Message): + r"""The request message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + + Attributes: + name (str): + Required. The flow name. Format: + ``projects//locations//agents//flows//validationResult``. + language_code (str): + If not specified, the agent's default + language is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class FlowValidationResult(proto.Message): + r"""The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + + Attributes: + name (str): + The unique identifier of the flow validation result. Format: + ``projects//locations//agents//flows//validationResult``. + validation_messages (Sequence[google.cloud.dialogflowcx_v3.types.ValidationMessage]): + Contains all validation messages. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Last time the flow was validated. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + validation_messages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=validation_message.ValidationMessage, + ) + update_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class ImportFlowRequest(proto.Message): + r"""The request message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + + Attributes: + parent (str): + Required. The agent to import the flow into. Format: + ``projects//locations//agents/``. + flow_uri (str): + The `Google Cloud + Storage `__ URI to + import flow from. The format of this URI must be + ``gs:///``. + flow_content (bytes): + Uncompressed raw byte content for flow. + import_option (google.cloud.dialogflowcx_v3.types.ImportFlowRequest.ImportOption): + Flow import mode. If not specified, ``KEEP`` is assumed. + """ + class ImportOption(proto.Enum): + r"""Import option.""" + IMPORT_OPTION_UNSPECIFIED = 0 + KEEP = 1 + FALLBACK = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + flow_uri = proto.Field( + proto.STRING, + number=2, + oneof='flow', + ) + flow_content = proto.Field( + proto.BYTES, + number=3, + oneof='flow', + ) + import_option = proto.Field( + proto.ENUM, + number=4, + enum=ImportOption, + ) + + +class ImportFlowResponse(proto.Message): + r"""The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + + Attributes: + flow (str): + The unique identifier of the new flow. Format: + ``projects//locations//agents//flows/``. + """ + + flow = proto.Field( + proto.STRING, + number=1, + ) + + +class ExportFlowRequest(proto.Message): + r"""The request message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + + Attributes: + name (str): + Required. The name of the flow to export. Format: + ``projects//locations//agents//flows/``. + flow_uri (str): + Optional. The `Google Cloud + Storage `__ URI to + export the flow to. The format of this URI must be + ``gs:///``. If left unspecified, + the serialized flow is returned inline. + include_referenced_flows (bool): + Optional. Whether to export flows referenced + by the specified flow. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + flow_uri = proto.Field( + proto.STRING, + number=2, + ) + include_referenced_flows = proto.Field( + proto.BOOL, + number=4, + ) + + +class ExportFlowResponse(proto.Message): + r"""The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + + Attributes: + flow_uri (str): + The URI to a file containing the exported flow. This field + is populated only if ``flow_uri`` is specified in + [ExportFlowRequest][google.cloud.dialogflow.cx.v3.ExportFlowRequest]. + flow_content (bytes): + Uncompressed raw byte content for flow. + """ + + flow_uri = proto.Field( + proto.STRING, + number=1, + oneof='flow', + ) + flow_content = proto.Field( + proto.BYTES, + number=2, + oneof='flow', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/fulfillment.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/fulfillment.py new file mode 100644 index 00000000..443e2aa7 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/fulfillment.py @@ -0,0 +1,200 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import response_message +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'Fulfillment', + }, +) + + +class Fulfillment(proto.Message): + r"""A fulfillment can do one or more of the following actions at the + same time: + + - Generate rich message responses. + - Set parameter values. + - Call the webhook. + + Fulfillments can be called at various stages in the + [Page][google.cloud.dialogflow.cx.v3.Page] or + [Form][google.cloud.dialogflow.cx.v3.Form] lifecycle. For example, + when a + [DetectIntentRequest][google.cloud.dialogflow.cx.v3.DetectIntentRequest] + drives a session to enter a new page, the page's entry fulfillment + can add a static response to the + [QueryResult][google.cloud.dialogflow.cx.v3.QueryResult] in the + returning + [DetectIntentResponse][google.cloud.dialogflow.cx.v3.DetectIntentResponse], + call the webhook (for example, to load user data from a database), + or both. + + Attributes: + messages (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage]): + The list of rich message responses to present + to the user. + webhook (str): + The webhook to call. Format: + ``projects//locations//agents//webhooks/``. + return_partial_responses (bool): + Whether Dialogflow should return currently + queued fulfillment response messages in + streaming APIs. If a webhook is specified, it + happens before Dialogflow invokes webhook. + Warning: + 1) This flag only affects streaming API. + Responses are still queued and returned once in + non-streaming API. + 2) The flag can be enabled in any fulfillment + but only the first 3 partial responses will be + returned. You may only want to apply it to + fulfillments that have slow webhooks. + tag (str): + The tag used by the webhook to identify which fulfillment is + being called. This field is required if ``webhook`` is + specified. + set_parameter_actions (Sequence[google.cloud.dialogflowcx_v3.types.Fulfillment.SetParameterAction]): + Set parameter values before executing the + webhook. + conditional_cases (Sequence[google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases]): + Conditional cases for this fulfillment. + """ + + class SetParameterAction(proto.Message): + r"""Setting a parameter value. + + Attributes: + parameter (str): + Display name of the parameter. + value (google.protobuf.struct_pb2.Value): + The new value of the parameter. A null value + clears the parameter. + """ + + parameter = proto.Field( + proto.STRING, + number=1, + ) + value = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + class ConditionalCases(proto.Message): + r"""A list of cascading if-else conditions. Cases are mutually + exclusive. The first one with a matching condition is selected, + all the rest ignored. + + Attributes: + cases (Sequence[google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases.Case]): + A list of cascading if-else conditions. + """ + + class Case(proto.Message): + r"""Each case has a Boolean condition. When it is evaluated to be + True, the corresponding messages will be selected and evaluated + recursively. + + Attributes: + condition (str): + The condition to activate and select this case. Empty means + the condition is always true. The condition is evaluated + against [form parameters][Form.parameters] or [session + parameters][SessionInfo.parameters]. + + See the `conditions + reference `__. + case_content (Sequence[google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases.Case.CaseContent]): + A list of case content. + """ + + class CaseContent(proto.Message): + r"""The list of messages or conditional cases to activate for + this case. + + Attributes: + message (google.cloud.dialogflowcx_v3.types.ResponseMessage): + Returned message. + additional_cases (google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases): + Additional cases to be evaluated. + """ + + message = proto.Field( + proto.MESSAGE, + number=1, + oneof='cases_or_message', + message=response_message.ResponseMessage, + ) + additional_cases = proto.Field( + proto.MESSAGE, + number=2, + oneof='cases_or_message', + message='Fulfillment.ConditionalCases', + ) + + condition = proto.Field( + proto.STRING, + number=1, + ) + case_content = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Fulfillment.ConditionalCases.Case.CaseContent', + ) + + cases = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Fulfillment.ConditionalCases.Case', + ) + + messages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=response_message.ResponseMessage, + ) + webhook = proto.Field( + proto.STRING, + number=2, + ) + return_partial_responses = proto.Field( + proto.BOOL, + number=8, + ) + tag = proto.Field( + proto.STRING, + number=3, + ) + set_parameter_actions = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=SetParameterAction, + ) + conditional_cases = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=ConditionalCases, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/intent.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/intent.py new file mode 100644 index 00000000..7ce4fe91 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/intent.py @@ -0,0 +1,476 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'IntentView', + 'Intent', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'GetIntentRequest', + 'CreateIntentRequest', + 'UpdateIntentRequest', + 'DeleteIntentRequest', + }, +) + + +class IntentView(proto.Enum): + r"""Represents the options for views of an intent. + An intent can be a sizable object. Therefore, we provide a + resource view that does not return training phrases in the + response. + """ + INTENT_VIEW_UNSPECIFIED = 0 + INTENT_VIEW_PARTIAL = 1 + INTENT_VIEW_FULL = 2 + + +class Intent(proto.Message): + r"""An intent represents a user's intent to interact with a + conversational agent. + You can provide information for the Dialogflow API to use to + match user input to an intent by adding training phrases (i.e., + examples of user input) to your intent. + + Attributes: + name (str): + The unique identifier of the intent. Required for the + [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent] + method. + [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent] + populates the name automatically. Format: + ``projects//locations//agents//intents/``. + display_name (str): + Required. The human-readable name of the + intent, unique within the agent. + training_phrases (Sequence[google.cloud.dialogflowcx_v3.types.Intent.TrainingPhrase]): + The collection of training phrases the agent + is trained on to identify the intent. + parameters (Sequence[google.cloud.dialogflowcx_v3.types.Intent.Parameter]): + The collection of parameters associated with + the intent. + priority (int): + The priority of this intent. Higher numbers represent higher + priorities. + + - If the supplied value is unspecified or 0, the service + translates the value to 500,000, which corresponds to the + ``Normal`` priority in the console. + - If the supplied value is negative, the intent is ignored + in runtime detect intent requests. + is_fallback (bool): + Indicates whether this is a fallback intent. + Currently only default fallback intent is + allowed in the agent, which is added upon agent + creation. + Adding training phrases to fallback intent is + useful in the case of requests that are + mistakenly matched, since training phrases + assigned to fallback intents act as negative + examples that triggers no-match event. + labels (Sequence[google.cloud.dialogflowcx_v3.types.Intent.LabelsEntry]): + The key/value metadata to label an intent. Labels can + contain lowercase letters, digits and the symbols '-' and + '_'. International characters are allowed, including letters + from unicase alphabets. Keys must start with a letter. Keys + and values can be no longer than 63 characters and no more + than 128 bytes. + + Prefix "sys-" is reserved for Dialogflow defined labels. + Currently allowed Dialogflow defined labels include: + + - sys-head + - sys-contextual The above labels do not require value. + "sys-head" means the intent is a head intent. + "sys.contextual" means the intent is a contextual intent. + description (str): + Human readable description for better + understanding an intent like its scope, content, + result etc. Maximum character limit: 140 + characters. + """ + + class TrainingPhrase(proto.Message): + r"""Represents an example that the agent is trained on to + identify the intent. + + Attributes: + id (str): + Output only. The unique identifier of the + training phrase. + parts (Sequence[google.cloud.dialogflowcx_v3.types.Intent.TrainingPhrase.Part]): + Required. The ordered list of training phrase parts. The + parts are concatenated in order to form the training phrase. + + Note: The API does not automatically annotate training + phrases like the Dialogflow Console does. + + Note: Do not forget to include whitespace at part + boundaries, so the training phrase is well formatted when + the parts are concatenated. + + If the training phrase does not need to be annotated with + parameters, you just need a single part with only the + [Part.text][google.cloud.dialogflow.cx.v3.Intent.TrainingPhrase.Part.text] + field set. + + If you want to annotate the training phrase, you must create + multiple parts, where the fields of each part are populated + in one of two ways: + + - ``Part.text`` is set to a part of the phrase that has no + parameters. + - ``Part.text`` is set to a part of the phrase that you + want to annotate, and the ``parameter_id`` field is set. + repeat_count (int): + Indicates how many times this example was + added to the intent. + """ + + class Part(proto.Message): + r"""Represents a part of a training phrase. + + Attributes: + text (str): + Required. The text for this part. + parameter_id (str): + The + [parameter][google.cloud.dialogflow.cx.v3.Intent.Parameter] + used to annotate this part of the training phrase. This + field is required for annotated parts of the training + phrase. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + parameter_id = proto.Field( + proto.STRING, + number=2, + ) + + id = proto.Field( + proto.STRING, + number=1, + ) + parts = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent.TrainingPhrase.Part', + ) + repeat_count = proto.Field( + proto.INT32, + number=3, + ) + + class Parameter(proto.Message): + r"""Represents an intent parameter. + + Attributes: + id (str): + Required. The unique identifier of the parameter. This field + is used by [training + phrases][google.cloud.dialogflow.cx.v3.Intent.TrainingPhrase] + to annotate their + [parts][google.cloud.dialogflow.cx.v3.Intent.TrainingPhrase.Part]. + entity_type (str): + Required. The entity type of the parameter. Format: + ``projects/-/locations/-/agents/-/entityTypes/`` + for system entity types (for example, + ``projects/-/locations/-/agents/-/entityTypes/sys.date``), + or + ``projects//locations//agents//entityTypes/`` + for developer entity types. + is_list (bool): + Indicates whether the parameter represents a + list of values. + redact (bool): + Indicates whether the parameter content should be redacted + in log. If redaction is enabled, the parameter content will + be replaced by parameter name during logging. Note: the + parameter content is subject to redaction if either + parameter level redaction or [entity type level + redaction][google.cloud.dialogflow.cx.v3.EntityType.redact] + is enabled. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.STRING, + number=2, + ) + is_list = proto.Field( + proto.BOOL, + number=3, + ) + redact = proto.Field( + proto.BOOL, + number=4, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + training_phrases = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TrainingPhrase, + ) + parameters = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Parameter, + ) + priority = proto.Field( + proto.INT32, + number=5, + ) + is_fallback = proto.Field( + proto.BOOL, + number=6, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + description = proto.Field( + proto.STRING, + number=8, + ) + + +class ListIntentsRequest(proto.Message): + r"""The request message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. + + Attributes: + parent (str): + Required. The agent to list all intents for. Format: + ``projects//locations//agents/``. + language_code (str): + The language to list intents for. The following fields are + language dependent: + + - ``Intent.training_phrases.parts.text`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + intent_view (google.cloud.dialogflowcx_v3.types.IntentView): + The resource view to apply to the returned + intent. + page_size (int): + The maximum number of items to return in a + single page. By default 100 and at most 1000. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + intent_view = proto.Field( + proto.ENUM, + number=5, + enum='IntentView', + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListIntentsResponse(proto.Message): + r"""The response message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. + + Attributes: + intents (Sequence[google.cloud.dialogflowcx_v3.types.Intent]): + The list of intents. There will be a maximum number of items + returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + intents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Intent', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetIntentRequest(proto.Message): + r"""The request message for + [Intents.GetIntent][google.cloud.dialogflow.cx.v3.Intents.GetIntent]. + + Attributes: + name (str): + Required. The name of the intent. Format: + ``projects//locations//agents//intents/``. + language_code (str): + The language to retrieve the intent for. The following + fields are language dependent: + + - ``Intent.training_phrases.parts.text`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateIntentRequest(proto.Message): + r"""The request message for + [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent]. + + Attributes: + parent (str): + Required. The agent to create an intent for. Format: + ``projects//locations//agents/``. + intent (google.cloud.dialogflowcx_v3.types.Intent): + Required. The intent to create. + language_code (str): + The language of the following fields in ``intent``: + + - ``Intent.training_phrases.parts.text`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + intent = proto.Field( + proto.MESSAGE, + number=2, + message='Intent', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateIntentRequest(proto.Message): + r"""The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent]. + + Attributes: + intent (google.cloud.dialogflowcx_v3.types.Intent): + Required. The intent to update. + language_code (str): + The language of the following fields in ``intent``: + + - ``Intent.training_phrases.parts.text`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + If the mask is not present, all fields will be + updated. + """ + + intent = proto.Field( + proto.MESSAGE, + number=1, + message='Intent', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteIntentRequest(proto.Message): + r"""The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3.Intents.DeleteIntent]. + + Attributes: + name (str): + Required. The name of the intent to delete. Format: + ``projects//locations//agents//intents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/page.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/page.py new file mode 100644 index 00000000..ef83e74c --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/page.py @@ -0,0 +1,731 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'Page', + 'Form', + 'EventHandler', + 'TransitionRoute', + 'ListPagesRequest', + 'ListPagesResponse', + 'GetPageRequest', + 'CreatePageRequest', + 'UpdatePageRequest', + 'DeletePageRequest', + }, +) + + +class Page(proto.Message): + r"""A Dialogflow CX conversation (session) can be described and + visualized as a state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your combined pages can + handle a complete conversation on the topics the flow is designed + for. At any given moment, exactly one page is the current page, the + current page is considered active, and the flow associated with that + page is considered active. Every flow has a special start page. When + a flow initially becomes active, the start page page becomes the + current page. For each conversational turn, the current page will + either stay the same or transition to another page. + + You configure each page to collect information from the end-user + that is relevant for the conversational state represented by the + page. + + For more information, see the `Page + guide `__. + + Attributes: + name (str): + The unique identifier of the page. Required for the + [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage] + method. + [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage] + populates the name automatically. Format: + ``projects//locations//agents//flows//pages/``. + display_name (str): + Required. The human-readable name of the + page, unique within the agent. + entry_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): + The fulfillment to call when the session is + entering the page. + form (google.cloud.dialogflowcx_v3.types.Form): + The form associated with the page, used for + collecting parameters relevant to the page. + transition_route_groups (Sequence[str]): + Ordered list of + [``TransitionRouteGroups``][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + associated with the page. Transition route groups must be + unique within a page. + + - If multiple transition routes within a page scope refer + to the same intent, then the precedence order is: page's + transition route -> page's transition route group -> + flow's transition routes. + + - If multiple transition route groups within a page contain + the same intent, then the first group in the ordered list + takes precedence. + + Format:\ ``projects//locations//agents//flows//transitionRouteGroups/``. + transition_routes (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRoute]): + A list of transitions for the transition rules of this page. + They route the conversation to another page in the same + flow, or another flow. + + When we are in a certain page, the TransitionRoutes are + evalauted in the following order: + + - TransitionRoutes defined in the page with intent + specified. + - TransitionRoutes defined in the [transition route + groups][google.cloud.dialogflow.cx.v3.Page.transition_route_groups] + with intent specified. + - TransitionRoutes defined in flow with intent specified. + - TransitionRoutes defined in the [transition route + groups][google.cloud.dialogflow.cx.v3.Flow.transition_route_groups] + with intent specified. + - TransitionRoutes defined in the page with only condition + specified. + - TransitionRoutes defined in the [transition route + groups][google.cloud.dialogflow.cx.v3.Page.transition_route_groups] + with only condition specified. + event_handlers (Sequence[google.cloud.dialogflowcx_v3.types.EventHandler]): + Handlers associated with the page to handle + events such as webhook errors, no match or no + input. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + entry_fulfillment = proto.Field( + proto.MESSAGE, + number=7, + message=fulfillment.Fulfillment, + ) + form = proto.Field( + proto.MESSAGE, + number=4, + message='Form', + ) + transition_route_groups = proto.RepeatedField( + proto.STRING, + number=11, + ) + transition_routes = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='TransitionRoute', + ) + event_handlers = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='EventHandler', + ) + + +class Form(proto.Message): + r"""A form is a data model that groups related parameters that can be + collected from the user. The process in which the agent prompts the + user and collects parameter values from the user is called form + filling. A form can be added to a + [page][google.cloud.dialogflow.cx.v3.Page]. When form filling is + done, the filled parameters will be written to the + [session][google.cloud.dialogflow.cx.v3.SessionInfo.parameters]. + + Attributes: + parameters (Sequence[google.cloud.dialogflowcx_v3.types.Form.Parameter]): + Parameters to collect from the user. + """ + + class Parameter(proto.Message): + r"""Represents a form parameter. + + Attributes: + display_name (str): + Required. The human-readable name of the + parameter, unique within the form. + required (bool): + Indicates whether the parameter is required. + Optional parameters will not trigger prompts; + however, they are filled if the user specifies + them. Required parameters must be filled before + form filling concludes. + entity_type (str): + Required. The entity type of the parameter. Format: + ``projects/-/locations/-/agents/-/entityTypes/`` + for system entity types (for example, + ``projects/-/locations/-/agents/-/entityTypes/sys.date``), + or + ``projects//locations//agents//entityTypes/`` + for developer entity types. + is_list (bool): + Indicates whether the parameter represents a + list of values. + fill_behavior (google.cloud.dialogflowcx_v3.types.Form.Parameter.FillBehavior): + Required. Defines fill behavior for the + parameter. + default_value (google.protobuf.struct_pb2.Value): + The default value of an optional parameter. + If the parameter is required, the default value + will be ignored. + redact (bool): + Indicates whether the parameter content should be redacted + in log. If redaction is enabled, the parameter content will + be replaced by parameter name during logging. Note: the + parameter content is subject to redaction if either + parameter level redaction or [entity type level + redaction][google.cloud.dialogflow.cx.v3.EntityType.redact] + is enabled. + """ + + class FillBehavior(proto.Message): + r"""Configuration for how the filling of a parameter should be + handled. + + Attributes: + initial_prompt_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): + Required. The fulfillment to provide the + initial prompt that the agent can present to the + user in order to fill the parameter. + reprompt_event_handlers (Sequence[google.cloud.dialogflowcx_v3.types.EventHandler]): + The handlers for parameter-level events, used to provide + reprompt for the parameter or transition to a different + page/flow. The supported events are: + + - ``sys.no-match-``, where N can be from 1 to 6 + - ``sys.no-match-default`` + - ``sys.no-input-``, where N can be from 1 to 6 + - ``sys.no-input-default`` + - ``sys.invalid-parameter`` + + ``initial_prompt_fulfillment`` provides the first prompt for + the parameter. + + If the user's response does not fill the parameter, a + no-match/no-input event will be triggered, and the + fulfillment associated with the + ``sys.no-match-1``/``sys.no-input-1`` handler (if defined) + will be called to provide a prompt. The + ``sys.no-match-2``/``sys.no-input-2`` handler (if defined) + will respond to the next no-match/no-input event, and so on. + + A ``sys.no-match-default`` or ``sys.no-input-default`` + handler will be used to handle all following + no-match/no-input events after all numbered + no-match/no-input handlers for the parameter are consumed. + + A ``sys.invalid-parameter`` handler can be defined to handle + the case where the parameter values have been + ``invalidated`` by webhook. For example, if the user's + response fill the parameter, however the parameter was + invalidated by webhook, the fulfillment associated with the + ``sys.invalid-parameter`` handler (if defined) will be + called to provide a prompt. + + If the event handler for the corresponding event can't be + found on the parameter, ``initial_prompt_fulfillment`` will + be re-prompted. + """ + + initial_prompt_fulfillment = proto.Field( + proto.MESSAGE, + number=3, + message=fulfillment.Fulfillment, + ) + reprompt_event_handlers = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='EventHandler', + ) + + display_name = proto.Field( + proto.STRING, + number=1, + ) + required = proto.Field( + proto.BOOL, + number=2, + ) + entity_type = proto.Field( + proto.STRING, + number=3, + ) + is_list = proto.Field( + proto.BOOL, + number=4, + ) + fill_behavior = proto.Field( + proto.MESSAGE, + number=7, + message='Form.Parameter.FillBehavior', + ) + default_value = proto.Field( + proto.MESSAGE, + number=9, + message=struct_pb2.Value, + ) + redact = proto.Field( + proto.BOOL, + number=11, + ) + + parameters = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Parameter, + ) + + +class EventHandler(proto.Message): + r"""An event handler specifies an + [event][google.cloud.dialogflow.cx.v3.EventHandler.event] that can + be handled during a session. When the specified event happens, the + following actions are taken in order: + + - If there is a + [``trigger_fulfillment``][google.cloud.dialogflow.cx.v3.EventHandler.trigger_fulfillment] + associated with the event, it will be called. + - If there is a + [``target_page``][google.cloud.dialogflow.cx.v3.EventHandler.target_page] + associated with the event, the session will transition into the + specified page. + - If there is a + [``target_flow``][google.cloud.dialogflow.cx.v3.EventHandler.target_flow] + associated with the event, the session will transition into the + specified flow. + + Attributes: + name (str): + Output only. The unique identifier of this + event handler. + event (str): + Required. The name of the event to handle. + trigger_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): + The fulfillment to call when the event + occurs. Handling webhook errors with a + fulfillment enabled with webhook could cause + infinite loop. It is invalid to specify such + fulfillment for a handler handling webhooks. + target_page (str): + The target page to transition to. Format: + ``projects//locations//agents//flows//pages/``. + target_flow (str): + The target flow to transition to. Format: + ``projects//locations//agents//flows/``. + """ + + name = proto.Field( + proto.STRING, + number=6, + ) + event = proto.Field( + proto.STRING, + number=4, + ) + trigger_fulfillment = proto.Field( + proto.MESSAGE, + number=5, + message=fulfillment.Fulfillment, + ) + target_page = proto.Field( + proto.STRING, + number=2, + oneof='target', + ) + target_flow = proto.Field( + proto.STRING, + number=3, + oneof='target', + ) + + +class TransitionRoute(proto.Message): + r"""A transition route specifies a + [intent][google.cloud.dialogflow.cx.v3.Intent] that can be matched + and/or a data condition that can be evaluated during a session. When + a specified transition is matched, the following actions are taken + in order: + + - If there is a + [``trigger_fulfillment``][google.cloud.dialogflow.cx.v3.TransitionRoute.trigger_fulfillment] + associated with the transition, it will be called. + - If there is a + [``target_page``][google.cloud.dialogflow.cx.v3.TransitionRoute.target_page] + associated with the transition, the session will transition into + the specified page. + - If there is a + [``target_flow``][google.cloud.dialogflow.cx.v3.TransitionRoute.target_flow] + associated with the transition, the session will transition into + the specified flow. + + Attributes: + name (str): + Output only. The unique identifier of this + transition route. + intent (str): + The unique identifier of an + [Intent][google.cloud.dialogflow.cx.v3.Intent]. Format: + ``projects//locations//agents//intents/``. + Indicates that the transition can only happen when the given + intent is matched. At least one of ``intent`` or + ``condition`` must be specified. When both ``intent`` and + ``condition`` are specified, the transition can only happen + when both are fulfilled. + condition (str): + The condition to evaluate against [form + parameters][google.cloud.dialogflow.cx.v3.Form.parameters] + or [session + parameters][google.cloud.dialogflow.cx.v3.SessionInfo.parameters]. + + See the `conditions + reference `__. + At least one of ``intent`` or ``condition`` must be + specified. When both ``intent`` and ``condition`` are + specified, the transition can only happen when both are + fulfilled. + trigger_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): + The fulfillment to call when the condition is satisfied. At + least one of ``trigger_fulfillment`` and ``target`` must be + specified. When both are defined, ``trigger_fulfillment`` is + executed first. + target_page (str): + The target page to transition to. Format: + ``projects//locations//agents//flows//pages/``. + target_flow (str): + The target flow to transition to. Format: + ``projects//locations//agents//flows/``. + """ + + name = proto.Field( + proto.STRING, + number=6, + ) + intent = proto.Field( + proto.STRING, + number=1, + ) + condition = proto.Field( + proto.STRING, + number=2, + ) + trigger_fulfillment = proto.Field( + proto.MESSAGE, + number=3, + message=fulfillment.Fulfillment, + ) + target_page = proto.Field( + proto.STRING, + number=4, + oneof='target', + ) + target_flow = proto.Field( + proto.STRING, + number=5, + oneof='target', + ) + + +class ListPagesRequest(proto.Message): + r"""The request message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. + + Attributes: + parent (str): + Required. The flow to list all pages for. Format: + ``projects//locations//agents//flows/``. + language_code (str): + The language to list pages for. The following fields are + language dependent: + + - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` + - + + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + page_size (int): + The maximum number of items to return in a + single page. By default 100 and at most 1000. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListPagesResponse(proto.Message): + r"""The response message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. + + Attributes: + pages (Sequence[google.cloud.dialogflowcx_v3.types.Page]): + The list of pages. There will be a maximum number of items + returned based on the page_size field in the request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + pages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Page', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetPageRequest(proto.Message): + r"""The request message for + [Pages.GetPage][google.cloud.dialogflow.cx.v3.Pages.GetPage]. + + Attributes: + name (str): + Required. The name of the page. Format: + ``projects//locations//agents//flows//pages/``. + language_code (str): + The language to retrieve the page for. The following fields + are language dependent: + + - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` + - + + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class CreatePageRequest(proto.Message): + r"""The request message for + [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage]. + + Attributes: + parent (str): + Required. The flow to create a page for. Format: + ``projects//locations//agents//flows/``. + page (google.cloud.dialogflowcx_v3.types.Page): + Required. The page to create. + language_code (str): + The language of the following fields in ``page``: + + - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` + - + + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page = proto.Field( + proto.MESSAGE, + number=2, + message='Page', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdatePageRequest(proto.Message): + r"""The request message for + [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage]. + + Attributes: + page (google.cloud.dialogflowcx_v3.types.Page): + Required. The page to update. + language_code (str): + The language of the following fields in ``page``: + + - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` + - + + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + If the mask is not present, all fields will be + updated. + """ + + page = proto.Field( + proto.MESSAGE, + number=1, + message='Page', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeletePageRequest(proto.Message): + r"""The request message for + [Pages.DeletePage][google.cloud.dialogflow.cx.v3.Pages.DeletePage]. + + Attributes: + name (str): + Required. The name of the page to delete. Format: + ``projects//locations//agents//Flows//pages/``. + force (bool): + This field has no effect for pages with no incoming + transitions. For pages with incoming transitions: + + - If ``force`` is set to false, an error will be returned + with message indicating the incoming transitions. + - If ``force`` is set to true, Dialogflow will remove the + page, as well as any transitions to the page (i.e. + [Target page][EventHandler.target_page] in event handlers + or [Target page][TransitionRoute.target_page] in + transition routes that point to this page will be + cleared). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/response_message.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/response_message.py new file mode 100644 index 00000000..d050a6d5 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/response_message.py @@ -0,0 +1,343 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'ResponseMessage', + }, +) + + +class ResponseMessage(proto.Message): + r"""Represents a response message that can be returned by a + conversational agent. + + Response messages are also used for output audio synthesis. The + approach is as follows: + + - If at least one OutputAudioText response is present, then all + OutputAudioText responses are linearly concatenated, and the + result is used for output audio synthesis. + - If the OutputAudioText responses are a mixture of text and SSML, + then the concatenated result is treated as SSML; otherwise, the + result is treated as either text or SSML as appropriate. The + agent designer should ideally use either text or SSML + consistently throughout the bot design. + - Otherwise, all Text responses are linearly concatenated, and the + result is used for output audio synthesis. + + This approach allows for more sophisticated user experience + scenarios, where the text displayed to the user may differ from what + is heard. + + Attributes: + text (google.cloud.dialogflowcx_v3.types.ResponseMessage.Text): + Returns a text response. + payload (google.protobuf.struct_pb2.Struct): + Returns a response containing a custom, + platform-specific payload. + conversation_success (google.cloud.dialogflowcx_v3.types.ResponseMessage.ConversationSuccess): + Indicates that the conversation succeeded. + output_audio_text (google.cloud.dialogflowcx_v3.types.ResponseMessage.OutputAudioText): + A text or ssml response that is + preferentially used for TTS output audio + synthesis, as described in the comment on the + ResponseMessage message. + live_agent_handoff (google.cloud.dialogflowcx_v3.types.ResponseMessage.LiveAgentHandoff): + Hands off conversation to a human agent. + end_interaction (google.cloud.dialogflowcx_v3.types.ResponseMessage.EndInteraction): + Output only. A signal that indicates the interaction with + the Dialogflow agent has ended. This message is generated by + Dialogflow only when the conversation reaches + ``END_SESSION`` page. It is not supposed to be defined by + the user. + + It's guaranteed that there is at most one such message in + each response. + play_audio (google.cloud.dialogflowcx_v3.types.ResponseMessage.PlayAudio): + Signal that the client should play an audio clip hosted at a + client-specific URI. Dialogflow uses this to construct + [mixed_audio][google.cloud.dialogflow.cx.v3.ResponseMessage.mixed_audio]. + However, Dialogflow itself does not try to read or process + the URI in any way. + mixed_audio (google.cloud.dialogflowcx_v3.types.ResponseMessage.MixedAudio): + Output only. An audio response message composed of both the + synthesized Dialogflow agent responses and responses defined + via + [play_audio][google.cloud.dialogflow.cx.v3.ResponseMessage.play_audio]. + This message is generated by Dialogflow only and not + supposed to be defined by the user. + """ + + class Text(proto.Message): + r"""The text response message. + + Attributes: + text (Sequence[str]): + Required. A collection of text responses. + allow_playback_interruption (bool): + Output only. Whether the playback of this + message can be interrupted by the end user's + speech and the client can then starts the next + Dialogflow request. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + allow_playback_interruption = proto.Field( + proto.BOOL, + number=2, + ) + + class LiveAgentHandoff(proto.Message): + r"""Indicates that the conversation should be handed off to a live + agent. + + Dialogflow only uses this to determine which conversations were + handed off to a human agent for measurement purposes. What else to + do with this signal is up to you and your handoff procedures. + + You may set this, for example: + + - In the + [entry_fulfillment][google.cloud.dialogflow.cx.v3.Page.entry_fulfillment] + of a [Page][google.cloud.dialogflow.cx.v3.Page] if entering the + page indicates something went extremely wrong in the + conversation. + - In a webhook response when you determine that the customer issue + can only be handled by a human. + + Attributes: + metadata (google.protobuf.struct_pb2.Struct): + Custom metadata for your handoff procedure. + Dialogflow doesn't impose any structure on this. + """ + + metadata = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + class ConversationSuccess(proto.Message): + r"""Indicates that the conversation succeeded, i.e., the bot handled the + issue that the customer talked to it about. + + Dialogflow only uses this to determine which conversations should be + counted as successful and doesn't process the metadata in this + message in any way. Note that Dialogflow also considers + conversations that get to the conversation end page as successful + even if they don't return + [ConversationSuccess][google.cloud.dialogflow.cx.v3.ResponseMessage.ConversationSuccess]. + + You may set this, for example: + + - In the + [entry_fulfillment][google.cloud.dialogflow.cx.v3.Page.entry_fulfillment] + of a [Page][google.cloud.dialogflow.cx.v3.Page] if entering the + page indicates that the conversation succeeded. + - In a webhook response when you determine that you handled the + customer issue. + + Attributes: + metadata (google.protobuf.struct_pb2.Struct): + Custom metadata. Dialogflow doesn't impose + any structure on this. + """ + + metadata = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + class OutputAudioText(proto.Message): + r"""A text or ssml response that is preferentially used for TTS + output audio synthesis, as described in the comment on the + ResponseMessage message. + + Attributes: + text (str): + The raw text to be synthesized. + ssml (str): + The SSML text to be synthesized. For more information, see + `SSML `__. + allow_playback_interruption (bool): + Output only. Whether the playback of this + message can be interrupted by the end user's + speech and the client can then starts the next + Dialogflow request. + """ + + text = proto.Field( + proto.STRING, + number=1, + oneof='source', + ) + ssml = proto.Field( + proto.STRING, + number=2, + oneof='source', + ) + allow_playback_interruption = proto.Field( + proto.BOOL, + number=3, + ) + + class EndInteraction(proto.Message): + r"""Indicates that interaction with the Dialogflow agent has + ended. This message is generated by Dialogflow only and not + supposed to be defined by the user. + + """ + + class PlayAudio(proto.Message): + r"""Specifies an audio clip to be played by the client as part of + the response. + + Attributes: + audio_uri (str): + Required. URI of the audio clip. Dialogflow + does not impose any validation on this value. It + is specific to the client that reads it. + allow_playback_interruption (bool): + Output only. Whether the playback of this + message can be interrupted by the end user's + speech and the client can then starts the next + Dialogflow request. + """ + + audio_uri = proto.Field( + proto.STRING, + number=1, + ) + allow_playback_interruption = proto.Field( + proto.BOOL, + number=2, + ) + + class MixedAudio(proto.Message): + r"""Represents an audio message that is composed of both segments + synthesized from the Dialogflow agent prompts and ones hosted + externally at the specified URIs. The external URIs are specified + via + [play_audio][google.cloud.dialogflow.cx.v3.ResponseMessage.play_audio]. + This message is generated by Dialogflow only and not supposed to be + defined by the user. + + Attributes: + segments (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage.MixedAudio.Segment]): + Segments this audio response is composed of. + """ + + class Segment(proto.Message): + r"""Represents one segment of audio. + + Attributes: + audio (bytes): + Raw audio synthesized from the Dialogflow + agent's response using the output config + specified in the request. + uri (str): + Client-specific URI that points to an audio + clip accessible to the client. Dialogflow does + not impose any validation on it. + allow_playback_interruption (bool): + Output only. Whether the playback of this + segment can be interrupted by the end user's + speech and the client should then start the next + Dialogflow request. + """ + + audio = proto.Field( + proto.BYTES, + number=1, + oneof='content', + ) + uri = proto.Field( + proto.STRING, + number=2, + oneof='content', + ) + allow_playback_interruption = proto.Field( + proto.BOOL, + number=3, + ) + + segments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ResponseMessage.MixedAudio.Segment', + ) + + text = proto.Field( + proto.MESSAGE, + number=1, + oneof='message', + message=Text, + ) + payload = proto.Field( + proto.MESSAGE, + number=2, + oneof='message', + message=struct_pb2.Struct, + ) + conversation_success = proto.Field( + proto.MESSAGE, + number=9, + oneof='message', + message=ConversationSuccess, + ) + output_audio_text = proto.Field( + proto.MESSAGE, + number=8, + oneof='message', + message=OutputAudioText, + ) + live_agent_handoff = proto.Field( + proto.MESSAGE, + number=10, + oneof='message', + message=LiveAgentHandoff, + ) + end_interaction = proto.Field( + proto.MESSAGE, + number=11, + oneof='message', + message=EndInteraction, + ) + play_audio = proto.Field( + proto.MESSAGE, + number=12, + oneof='message', + message=PlayAudio, + ) + mixed_audio = proto.Field( + proto.MESSAGE, + number=13, + oneof='message', + message=MixedAudio, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/security_settings.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/security_settings.py new file mode 100644 index 00000000..33fecd09 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/security_settings.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'GetSecuritySettingsRequest', + 'UpdateSecuritySettingsRequest', + 'ListSecuritySettingsRequest', + 'ListSecuritySettingsResponse', + 'CreateSecuritySettingsRequest', + 'DeleteSecuritySettingsRequest', + 'SecuritySettings', + }, +) + + +class GetSecuritySettingsRequest(proto.Message): + r"""The request message for + [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings]. + + Attributes: + name (str): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSecuritySettingsRequest(proto.Message): + r"""The request message for + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings]. + + Attributes: + security_settings (google.cloud.dialogflowcx_v3.types.SecuritySettings): + Required. [SecuritySettings] object that contains values for + each of the fields to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. If the mask is not present, all + fields will be updated. + """ + + security_settings = proto.Field( + proto.MESSAGE, + number=1, + message='SecuritySettings', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListSecuritySettingsRequest(proto.Message): + r"""The request message for [SecuritySettings.ListSecuritySettings][]. + + Attributes: + parent (str): + Required. The location to list all security settings for. + Format: ``projects//locations/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 and at most 100. + page_token (str): + The next_page_token value returned from a previous list + request. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSecuritySettingsResponse(proto.Message): + r"""The response message for [SecuritySettings.ListSecuritySettings][]. + + Attributes: + security_settings (Sequence[google.cloud.dialogflowcx_v3.types.SecuritySettings]): + The list of security settings. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + security_settings = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SecuritySettings', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSecuritySettingsRequest(proto.Message): + r"""The request message for [SecuritySettings.CreateSecuritySettings][]. + + Attributes: + parent (str): + Required. The location to create an + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + for. Format: + ``projects//locations/``. + security_settings (google.cloud.dialogflowcx_v3.types.SecuritySettings): + Required. The security settings to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + security_settings = proto.Field( + proto.MESSAGE, + number=2, + message='SecuritySettings', + ) + + +class DeleteSecuritySettingsRequest(proto.Message): + r"""The request message for [SecuritySettings.DeleteSecuritySettings][]. + + Attributes: + name (str): + Required. The name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + to delete. Format: + ``projects//locations//securitySettings/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class SecuritySettings(proto.Message): + r"""Represents the settings related to security issues, such as + data redaction and data retention. It may take hours for updates + on the settings to propagate to all the related components and + take effect. + + Attributes: + name (str): + Resource name of the settings. Required for the + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings] + method. + [SecuritySettingsService.CreateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.CreateSecuritySettings] + populates the name automatically. Format: + ``projects//locations//securitySettings/``. + display_name (str): + Required. The human-readable name of the + security settings, unique within the location. + redaction_strategy (google.cloud.dialogflowcx_v3.types.SecuritySettings.RedactionStrategy): + Strategy that defines how we do redaction. + redaction_scope (google.cloud.dialogflowcx_v3.types.SecuritySettings.RedactionScope): + Defines the data for which Dialogflow applies + redaction. Dialogflow does not redact data that + it does not have access to – for example, Cloud + logging. + inspect_template (str): + `DLP `__ inspect template + name. Use this template to define inspect base settings. + + If empty, we use the default DLP inspect config. + + The template name will have one of the following formats: + ``projects//locations//inspectTemplates/