File: router_worker_crud_ops.py

package info (click to toggle)
python-azure 20230112%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 749,544 kB
  • sloc: python: 6,815,827; javascript: 287; makefile: 195; xml: 109; sh: 105
file content (274 lines) | stat: -rw-r--r-- 9,838 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
# -------------------------------------------------------------------------
# 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.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.py
    Set the environment variables with your own values before running the sample:
    1) AZURE_COMMUNICATION_SERVICE_ENDPOINT - Communication Service endpoint url
"""

import os


class RouterWorkerSamples(object):
    endpoint = os.environ.get("AZURE_COMMUNICATION_SERVICE_ENDPOINT", None)
    if not endpoint:
        raise ValueError("Set AZURE_COMMUNICATION_SERVICE_ENDPOINT env before run this sample.")

    _worker_id = "sample_worker"
    _distribution_policy_id = "sample_dp_policy"

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

        from azure.communication.jobrouter import (
            RouterAdministrationClient,
            LongestIdleMode,
            DistributionPolicy
        )
        router_admin_client = RouterAdministrationClient.from_connection_string(conn_str = connection_string)
        distribution_policy = router_admin_client.create_distribution_policy(
            distribution_policy_id = distribution_policy_id,
            distribution_policy = DistributionPolicy(
                offer_ttl_seconds = 10 * 60,
                mode = LongestIdleMode(
                    min_concurrent_offers = 1,
                    max_concurrent_offers = 1
                )
            )
        )
        print(f"Sample setup completed: Created distribution policy")

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

        from azure.communication.jobrouter import (
            RouterAdministrationClient,
            JobQueue
        )

        router_admin_client = RouterAdministrationClient.from_connection_string(conn_str = connection_string)
        job_queue1: JobQueue = router_admin_client.create_queue(
            queue_id = "worker-q-1",
            queue = JobQueue(
                distribution_policy_id = distribution_policy_id,
            )
        )

        job_queue2: JobQueue = router_admin_client.create_queue(
            queue_id = "worker-q-2",
            queue = JobQueue(
                distribution_policy_id = distribution_policy_id,
            )
        )

        job_queue3: JobQueue = router_admin_client.create_queue(
            queue_id = "worker-q-3",
            queue = JobQueue(
                distribution_policy_id = distribution_policy_id,
            )
        )

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

    def create_worker(self):
        connection_string = self.endpoint
        worker_id = self._worker_id
        # [START create_worker]
        from azure.communication.jobrouter import (
            RouterClient,
            RouterWorker,
            QueueAssignment,
            ChannelConfiguration,
        )

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

        router_worker: RouterWorker = router_client.create_worker(
            worker_id = worker_id,
            router_worker = RouterWorker(
                total_capacity = 100,
                queue_assignments = {
                    "worker-q-1": QueueAssignment(),
                    "worker-q-2": QueueAssignment()
                },
                channel_configurations = {
                    "WebChat": ChannelConfiguration(capacity_cost_per_job = 1),
                    "WebChatEscalated": ChannelConfiguration(capacity_cost_per_job = 20),
                    "Voip": ChannelConfiguration(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]

    def update_worker(self):
        connection_string = self.endpoint
        worker_id = self._worker_id
        # [START update_worker]
        from azure.communication.jobrouter import (
            RouterClient,
            RouterWorker,
            QueueAssignment,
            ChannelConfiguration,
        )

        # set `connection_string` to an existing ACS endpoint
        router_client: RouterClient = RouterClient.from_connection_string(conn_str = connection_string)
        print("RouterClient 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

        updated_router_worker: RouterWorker = router_client.update_worker(
            worker_id = worker_id,
            queue_assignments = {
                "worker-q-3": QueueAssignment()
            },
            channel_configurations = {
                "WebChatEscalated": ChannelConfiguration(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]

    def get_worker(self):
        connection_string = self.endpoint
        worker_id = self._worker_id
        # [START get_worker]
        from azure.communication.jobrouter import RouterClient

        router_client = RouterClient.from_connection_string(conn_str = connection_string)

        router_worker = router_client.get_worker(worker_id = worker_id)

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

    def register_worker(self):
        connection_string = self.endpoint
        worker_id = self._worker_id
        # [START register_worker]
        from azure.communication.jobrouter import RouterClient

        router_client = RouterClient.from_connection_string(conn_str = connection_string)

        router_worker = router_client.update_worker(
            worker_id = 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]

    def deregister_worker(self):
        connection_string = self.endpoint
        worker_id = self._worker_id
        # [START deregister_worker]
        from azure.communication.jobrouter import RouterClient

        router_client = RouterClient.from_connection_string(conn_str = connection_string)

        router_worker = router_client.update_worker(
            worker_id = worker_id,
            available_for_offers = False
        )

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

    def list_workers(self):
        connection_string = self.endpoint
        # [START list_workers]
        from azure.communication.jobrouter import RouterClient

        router_client = RouterClient.from_connection_string(conn_str = connection_string)

        router_worker_iterator = router_client.list_workers()

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

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

    def list_workers_batched(self):
        connection_string = self.endpoint
        # [START list_workers_batched]
        from azure.communication.jobrouter import RouterClient

        router_client = RouterClient.from_connection_string(conn_str = connection_string)

        router_worker_iterator = router_client.list_workers(results_per_page = 10)

        for worker_page in router_worker_iterator.by_page():
            workers_in_page = list(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.router_worker.id}")

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

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

        # [START delete_worker]
        from azure.communication.jobrouter import RouterClient

        router_client = RouterClient.from_connection_string(conn_str = connection_string)

        router_client.delete_worker(worker_id = worker_id)

        # [END delete_worker]


if __name__ == '__main__':
    sample = RouterWorkerSamples()
    sample.setup_distribution_policy()
    sample.setup_queues()
    sample.create_worker()
    sample.update_worker()
    sample.get_worker()
    sample.register_worker()
    sample.deregister_worker()
    sample.list_workers()
    sample.list_workers_batched()
    sample.clean_up()