File: router_worker_crud_ops_async.py

package info (click to toggle)
python-azure 20250603%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 851,724 kB
  • sloc: python: 7,362,925; ansic: 804; javascript: 287; makefile: 195; sh: 145; xml: 109
file content (297 lines) | stat: -rw-r--r-- 11,981 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

"""
FILE: router_worker_crud_ops_async.py
DESCRIPTION:
    These samples demonstrates how to create Workers used in ACS JobRouter.
    You need a valid connection string to an Azure Communication Service to execute the sample

USAGE:
    python router_worker_crud_ops_async.py
    Set the environment variables with your own values before running the sample:
    1) AZURE_COMMUNICATION_SERVICE_CONNECTION_STRING - Communication Service connection string
"""

import os
import asyncio


class RouterWorkerSamplesAsync(object):
    connection_string = os.environ["AZURE_COMMUNICATION_SERVICE_CONNECTION_STRING"]

    _worker_id = "sample_worker"
    _distribution_policy_id = "sample_dp_policy"

    async def setup_distribution_policy(self):
        connection_string = self.connection_string
        distribution_policy_id = self._distribution_policy_id

        from azure.communication.jobrouter.aio import JobRouterAdministrationClient
        from azure.communication.jobrouter.models import LongestIdleMode, DistributionPolicy

        router_admin_client = JobRouterAdministrationClient.from_connection_string(conn_str=connection_string)

        async with router_admin_client:
            distribution_policy = await router_admin_client.upsert_distribution_policy(
                distribution_policy_id,
                DistributionPolicy(
                    offer_expires_after_seconds=10 * 60,
                    mode=LongestIdleMode(min_concurrent_offers=1, max_concurrent_offers=1),
                ),
            )
            print(f"Sample setup completed: Created distribution policy")

    async def setup_queues(self):
        connection_string = self.connection_string
        distribution_policy_id = self._distribution_policy_id

        from azure.communication.jobrouter.aio import JobRouterAdministrationClient
        from azure.communication.jobrouter.models import RouterQueue

        router_admin_client = JobRouterAdministrationClient.from_connection_string(conn_str=connection_string)

        async with router_admin_client:
            job_queue1: RouterQueue = await router_admin_client.upsert_queue(
                "worker-q-1",
                RouterQueue(
                    distribution_policy_id=distribution_policy_id,
                ),
            )

            job_queue2: RouterQueue = await router_admin_client.upsert_queue(
                "worker-q-2",
                RouterQueue(
                    distribution_policy_id=distribution_policy_id,
                ),
            )

            job_queue3: RouterQueue = await router_admin_client.upsert_queue(
                "worker-q-3",
                RouterQueue(
                    distribution_policy_id=distribution_policy_id,
                ),
            )

            print(f"Sample setup completed: Created queues")

    async def create_worker(self):
        connection_string = self.connection_string
        worker_id = self._worker_id
        # [START create_worker_async]
        from azure.communication.jobrouter.aio import JobRouterClient
        from azure.communication.jobrouter.models import (
            RouterWorker,
            RouterChannel,
        )

        # set `connection_string` to an existing ACS endpoint
        router_client = JobRouterClient.from_connection_string(conn_str=connection_string)
        print("JobRouterClient created successfully!")

        async with router_client:
            router_worker: RouterWorker = await router_client.upsert_worker(
                worker_id,
                RouterWorker(
                    capacity=100,
                    queues=["worker-q-1", "worker-q-2"],
                    channels=[
                        RouterChannel(channel_id="WebChat", capacity_cost_per_job=1),
                        RouterChannel(channel_id="WebChatEscalated", capacity_cost_per_job=20),
                        RouterChannel(channel_id="Voip", capacity_cost_per_job=100),
                    ],
                    labels={"Location": "NA", "English": 7, "O365": True, "Xbox_Support": False},
                    tags={"Name": "John Doe", "Department": "IT_HelpDesk"},
                ),
            )

            print(f"Router worker successfully created with id: {router_worker.id}")

        # [END create_worker_async]

    async def create_worker_w_limit_concurrent_offers(self):
        connection_string = self.endpoint
        worker_id = self._worker_id
        # [START create_worker_w_limit_concurrent_offers_async]
        from azure.communication.jobrouter.aio import JobRouterClient
        from azure.communication.jobrouter.models import (
            RouterWorker,
            RouterChannel,
        )

        # set `connection_string` to an existing ACS endpoint
        router_client = JobRouterClient.from_connection_string(conn_str=connection_string)
        print("JobRouterClient created successfully!")

        async with router_client:
            router_worker: RouterWorker = await router_client.upsert_worker(
                worker_id,
                RouterWorker(
                    capacity=100,
                    queues=["worker-q-1", "worker-q-2"],
                    channels=[
                        RouterChannel(channel_id="WebChat", capacity_cost_per_job=1),
                        RouterChannel(channel_id="WebChatEscalated", capacity_cost_per_job=20),
                        RouterChannel(channel_id="Voip", capacity_cost_per_job=100),
                    ],
                    labels={"Location": "NA", "English": 7, "O365": True, "Xbox_Support": False},
                    tags={"Name": "John Doe", "Department": "IT_HelpDesk"},
                    max_concurrent_offers=1,
                ),
            )

            print(f"Router worker successfully created with id: {router_worker.id}")

        # [END create_worker_w_limit_concurrent_offers_async]

    async def update_worker(self):
        connection_string = self.connection_string
        worker_id = self._worker_id
        # [START update_worker_async]
        from azure.communication.jobrouter.aio import JobRouterClient
        from azure.communication.jobrouter.models import (
            RouterWorker,
            RouterChannel,
        )

        # set `connection_string` to an existing ACS endpoint
        router_client: JobRouterClient = JobRouterClient.from_connection_string(conn_str=connection_string)
        print("JobRouterClient created successfully!")

        # we are going to
        # 1. Assign the worker to another queue
        # 2. Modify an value of label: `O365`
        # 3. Delete label: `Xbox_Support`
        # 4. Add a new label: `Xbox_Support_EN` and set value true
        # 5. Increase capacityCostPerJob for channel `WebChatEscalated` to 50

        async with router_client:
            updated_router_worker: RouterWorker = await router_client.upsert_worker(
                worker_id,
                queues=["worker-q-3"],
                channels=[RouterChannel(channel_id="WebChatEscalated", capacity_cost_per_job=50)],
                labels={"O365": "Supported", "Xbox_Support": None, "Xbox_Support_EN": True},
            )

            print(f"Router worker successfully update with labels {updated_router_worker.labels}")
        # [END update_worker_async]

    async def get_worker(self):
        connection_string = self.connection_string
        worker_id = self._worker_id
        # [START get_worker_async]
        from azure.communication.jobrouter.aio import JobRouterClient

        router_client = JobRouterClient.from_connection_string(conn_str=connection_string)

        async with router_client:
            router_worker = await router_client.get_worker(worker_id=worker_id)

            print(f"Successfully fetched router worker with id: {router_worker.id}")
        # [END get_worker_async]

    async def register_worker(self):
        connection_string = self.connection_string
        worker_id = self._worker_id
        # [START register_worker_async]
        from azure.communication.jobrouter.aio import JobRouterClient

        router_client = JobRouterClient.from_connection_string(conn_str=connection_string)

        async with router_client:
            router_worker = await router_client.upsert_worker(worker_id, available_for_offers=True)

            print(
                f"Successfully registered router worker with id: {router_worker.id} with status: {router_worker.state}"
            )
        # [END register_worker_async]

    async def deregister_worker(self):
        connection_string = self.connection_string
        worker_id = self._worker_id
        # [START deregister_worker_async]
        from azure.communication.jobrouter.aio import JobRouterClient

        router_client = JobRouterClient.from_connection_string(conn_str=connection_string)

        async with router_client:
            router_worker = await router_client.upsert_worker(worker_id, available_for_offers=False)

            print(
                f"Successfully de-registered router worker with id: {router_worker.id} "
                f"with status: {router_worker.state}"
            )
        # [END deregister_worker_async]

    async def list_workers(self):
        connection_string = self.connection_string
        # [START list_workers_async]
        from azure.communication.jobrouter.aio import JobRouterClient

        router_client = JobRouterClient.from_connection_string(conn_str=connection_string)

        async with router_client:
            router_worker_iterator = router_client.list_workers()

            async for w in router_worker_iterator:
                print(f"Retrieved worker with id: {w.id}")

            print(f"Successfully completed fetching workers")
        # [END list_workers_async]

    async def list_workers_batched(self):
        connection_string = self.connection_string
        # [START list_workers_batched_async]
        from azure.communication.jobrouter.aio import JobRouterClient

        router_client = JobRouterClient.from_connection_string(conn_str=connection_string)

        async with router_client:
            router_worker_iterator = router_client.list_workers(results_per_page=10)

            async for worker_page in router_worker_iterator.by_page():
                workers_in_page = [i async for i in worker_page]
                print(f"Retrieved {len(workers_in_page)} workers in current page")

                for w in workers_in_page:
                    print(f"Retrieved worker with id: {w.id}")

            print(f"Successfully completed fetching workers")
        # [END list_workers_batched_async]

    async def clean_up(self):
        connection_string = self.connection_string
        worker_id = self._worker_id

        # [START delete_worker_async]
        from azure.communication.jobrouter.aio import JobRouterClient

        router_client = JobRouterClient.from_connection_string(conn_str=connection_string)

        async with router_client:
            await router_client.delete_worker(worker_id=worker_id)

        # [END delete_worker_async]


async def main():
    sample = RouterWorkerSamplesAsync()
    await sample.setup_distribution_policy()
    await sample.setup_queues()
    await sample.create_worker()
    await sample.create_worker_w_limit_concurrent_offers()
    await sample.update_worker()
    await sample.get_worker()
    await sample.register_worker()
    await sample.deregister_worker()
    await sample.list_workers()
    await sample.list_workers_batched()
    await sample.clean_up()


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())