or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdindex.mdorganization-events.mdorganization-impacts.mdservice-health-events.md

async-operations.mddocs/

0

# Async Operations

1

2

All Service Health API operations are available in asynchronous versions for non-blocking execution in async/await environments. The async client provides the same functionality as the synchronous client but with async/await support.

3

4

## Capabilities

5

6

### Async Client Initialization

7

8

Initialize the asynchronous Service Health client for non-blocking operations.

9

10

```python { .api }

11

class ServiceHealthAsyncClient:

12

"""Asynchronous client for Google Cloud Service Health API."""

13

14

def __init__(

15

self,

16

*,

17

credentials: Optional[ga_credentials.Credentials] = None,

18

transport: Optional[Union[str, ServiceHealthAsyncTransport, Callable]] = None,

19

client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,

20

client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,

21

) -> None: ...

22

```

23

24

**Usage Example:**

25

26

```python

27

import asyncio

28

from google.cloud.servicehealth import ServiceHealthAsyncClient

29

30

async def main():

31

# Initialize async client

32

async_client = ServiceHealthAsyncClient()

33

34

# Use in async context

35

parent = "projects/my-project/locations/global"

36

events = async_client.list_events(parent=parent)

37

38

async for event in events:

39

print(f"Event: {event.title}")

40

41

# Close the client when done

42

await async_client.transport.close()

43

44

# Run async main

45

asyncio.run(main())

46

```

47

48

### Async Event Operations

49

50

All event operations are available as async methods with the same signatures as their synchronous counterparts.

51

52

```python { .api }

53

# Async event methods

54

async def list_events(

55

self,

56

request: Optional[Union[ListEventsRequest, dict]] = None,

57

*,

58

parent: Optional[str] = None,

59

retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,

60

timeout: Union[float, object] = gapic_v1.method.DEFAULT,

61

metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),

62

) -> ListEventsAsyncPager: ...

63

64

async def get_event(

65

self,

66

request: Optional[Union[GetEventRequest, dict]] = None,

67

*,

68

name: Optional[str] = None,

69

retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,

70

timeout: Union[float, object] = gapic_v1.method.DEFAULT,

71

metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),

72

) -> Event: ...

73

```

74

75

**Usage Example:**

76

77

```python

78

import asyncio

79

from google.cloud.servicehealth import ServiceHealthAsyncClient, EventView

80

81

async def process_service_events():

82

async_client = ServiceHealthAsyncClient()

83

84

try:

85

# List events asynchronously

86

parent = "projects/my-project/locations/global"

87

events_pager = async_client.list_events(

88

parent=parent,

89

view=EventView.EVENT_VIEW_FULL

90

)

91

92

async for event in events_pager:

93

print(f"Processing event: {event.title}")

94

95

# Process each event asynchronously

96

await process_event_details(event)

97

98

# Get specific event

99

if events_pager: # If we have events

100

event_name = "projects/my-project/locations/global/events/event-123"

101

specific_event = await async_client.get_event(name=event_name)

102

print(f"Specific event: {specific_event.title}")

103

104

finally:

105

await async_client.transport.close()

106

107

async def process_event_details(event):

108

"""Process individual event details asynchronously."""

109

# Simulate async processing

110

await asyncio.sleep(0.1)

111

print(f" State: {event.state}")

112

print(f" Category: {event.category}")

113

for impact in event.event_impacts:

114

print(f" Impact: {impact.product.product_name}")

115

116

asyncio.run(process_service_events())

117

```

118

119

### Async Organization Operations

120

121

Organization-level operations are also available asynchronously.

122

123

```python { .api }

124

# Async organization event methods

125

async def list_organization_events(

126

self,

127

request: Optional[Union[ListOrganizationEventsRequest, dict]] = None,

128

*,

129

parent: Optional[str] = None,

130

retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,

131

timeout: Union[float, object] = gapic_v1.method.DEFAULT,

132

metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),

133

) -> ListOrganizationEventsAsyncPager: ...

134

135

async def get_organization_event(

136

self,

137

request: Optional[Union[GetOrganizationEventRequest, dict]] = None,

138

*,

139

name: Optional[str] = None,

140

retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,

141

timeout: Union[float, object] = gapic_v1.method.DEFAULT,

142

metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),

143

) -> OrganizationEvent: ...

144

145

# Async organization impact methods

146

async def list_organization_impacts(

147

self,

148

request: Optional[Union[ListOrganizationImpactsRequest, dict]] = None,

149

*,

150

parent: Optional[str] = None,

151

retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,

152

timeout: Union[float, object] = gapic_v1.method.DEFAULT,

153

metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),

154

) -> ListOrganizationImpactsAsyncPager: ...

155

156

async def get_organization_impact(

157

self,

158

request: Optional[Union[GetOrganizationImpactRequest, dict]] = None,

159

*,

160

name: Optional[str] = None,

161

retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,

162

timeout: Union[float, object] = gapic_v1.method.DEFAULT,

163

metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),

164

) -> OrganizationImpact: ...

165

```

166

167

## Async Pagers

168

169

Async pagers provide iteration over paginated results using async iteration protocols.

170

171

```python { .api }

172

class ListEventsAsyncPager:

173

"""Async iterator for paginated event results."""

174

def __aiter__(self) -> AsyncIterator[Event]: ...

175

176

class ListOrganizationEventsAsyncPager:

177

"""Async iterator for paginated organization event results."""

178

def __aiter__(self) -> AsyncIterator[OrganizationEvent]: ...

179

180

class ListOrganizationImpactsAsyncPager:

181

"""Async iterator for paginated organization impact results."""

182

def __aiter__(self) -> AsyncIterator[OrganizationImpact]: ...

183

```

184

185

**Usage Example:**

186

187

```python

188

async def process_all_organization_data():

189

async_client = ServiceHealthAsyncClient()

190

191

try:

192

org_id = "123456789"

193

194

# Process organization events

195

events_parent = f"organizations/{org_id}/locations/global"

196

events_pager = async_client.list_organization_events(parent=events_parent)

197

198

async for event in events_pager:

199

print(f"Organization Event: {event.title}")

200

201

# Process organization impacts

202

impacts_parent = f"organizations/{org_id}/locations/global/organizationImpacts"

203

impacts_pager = async_client.list_organization_impacts(parent=impacts_parent)

204

205

async for impact in impacts_pager:

206

print(f"Impact on: {impact.asset.asset_name}")

207

208

finally:

209

await async_client.transport.close()

210

211

asyncio.run(process_all_organization_data())

212

```

213

214

## Concurrent Operations

215

216

Leverage asyncio for concurrent operations to improve performance when processing multiple requests.

217

218

```python

219

import asyncio

220

from google.cloud.servicehealth import ServiceHealthAsyncClient

221

222

async def fetch_multiple_events_concurrently():

223

"""Fetch multiple events concurrently for improved performance."""

224

async_client = ServiceHealthAsyncClient()

225

226

try:

227

# Define multiple event names to fetch

228

event_names = [

229

"projects/project-1/locations/global/events/event-123",

230

"projects/project-2/locations/global/events/event-456",

231

"projects/project-3/locations/global/events/event-789"

232

]

233

234

# Create concurrent tasks

235

tasks = [

236

async_client.get_event(name=event_name)

237

for event_name in event_names

238

]

239

240

# Execute all tasks concurrently

241

events = await asyncio.gather(*tasks, return_exceptions=True)

242

243

# Process results

244

for i, result in enumerate(events):

245

if isinstance(result, Exception):

246

print(f"Error fetching {event_names[i]}: {result}")

247

else:

248

print(f"Event: {result.title} - State: {result.state}")

249

250

finally:

251

await async_client.transport.close()

252

253

asyncio.run(fetch_multiple_events_concurrently())

254

```

255

256

## Async Context Manager

257

258

Use the async client as a context manager for automatic resource cleanup.

259

260

```python

261

async def monitor_with_context_manager():

262

"""Use async client with context manager for automatic cleanup."""

263

async with ServiceHealthAsyncClient() as client:

264

parent = "projects/my-project/locations/global"

265

266

# Client will be automatically closed when exiting context

267

events = client.list_events(parent=parent)

268

async for event in events:

269

if event.state == Event.State.ACTIVE:

270

print(f"Active Event: {event.title}")

271

272

# Get full details

273

full_event = await client.get_event(name=event.name)

274

print(f"Description: {full_event.description}")

275

276

asyncio.run(monitor_with_context_manager())

277

```

278

279

## Error Handling in Async Operations

280

281

Handle exceptions properly in async operations with retry logic.

282

283

```python

284

import asyncio

285

from google.api_core import exceptions as api_exceptions

286

from google.cloud.servicehealth import ServiceHealthAsyncClient

287

288

async def robust_async_operations():

289

"""Demonstrate robust error handling in async operations."""

290

async_client = ServiceHealthAsyncClient()

291

292

try:

293

# Retry logic for transient errors

294

max_retries = 3

295

for attempt in range(max_retries):

296

try:

297

parent = "projects/my-project/locations/global"

298

events = async_client.list_events(parent=parent)

299

300

async for event in events:

301

print(f"Event: {event.title}")

302

303

break # Success, exit retry loop

304

305

except api_exceptions.ServiceUnavailable as e:

306

if attempt < max_retries - 1:

307

wait_time = 2 ** attempt # Exponential backoff

308

print(f"Service unavailable, retrying in {wait_time}s...")

309

await asyncio.sleep(wait_time)

310

else:

311

print(f"Service unavailable after {max_retries} attempts: {e}")

312

raise

313

314

except api_exceptions.PermissionDenied as e:

315

print(f"Permission denied: {e}")

316

break # Don't retry permission errors

317

318

except Exception as e:

319

print(f"Unexpected error: {e}")

320

break

321

322

finally:

323

await async_client.transport.close()

324

325

asyncio.run(robust_async_operations())

326

```

327

328

## Async Streaming and Real-time Monitoring

329

330

Implement real-time monitoring using async operations with periodic polling.

331

332

```python

333

import asyncio

334

from datetime import datetime, timedelta

335

from google.cloud.servicehealth import ServiceHealthAsyncClient, EventView

336

337

async def real_time_event_monitor(project_id: str, poll_interval: int = 60):

338

"""Monitor service health events in real-time using async operations."""

339

async_client = ServiceHealthAsyncClient()

340

341

try:

342

parent = f"projects/{project_id}/locations/global"

343

last_check = datetime.utcnow()

344

345

while True:

346

try:

347

# Get events updated since last check

348

time_filter = f'update_time>="{last_check.isoformat()}Z"'

349

350

recent_events = async_client.list_events(

351

parent=parent,

352

filter=time_filter,

353

view=EventView.EVENT_VIEW_FULL

354

)

355

356

async for event in recent_events:

357

print(f"Event Update: {event.title}")

358

print(f"State: {event.state}")

359

print(f"Last Update: {event.update_time}")

360

361

# Check for new updates

362

if event.updates:

363

latest_update = event.updates[-1]

364

print(f"Latest Update: {latest_update.title}")

365

366

last_check = datetime.utcnow()

367

368

except Exception as e:

369

print(f"Error during monitoring: {e}")

370

371

# Wait before next poll

372

await asyncio.sleep(poll_interval)

373

374

except KeyboardInterrupt:

375

print("Monitoring stopped by user")

376

finally:

377

await async_client.transport.close()

378

379

# Run the monitor

380

asyncio.run(real_time_event_monitor("my-project", poll_interval=30))

381

```

382

383

## Performance Considerations

384

385

When using async operations, consider these performance optimization strategies:

386

387

1. **Connection Pooling**: The async client automatically manages connection pooling

388

2. **Concurrent Requests**: Use `asyncio.gather()` for concurrent API calls

389

3. **Batch Processing**: Process multiple items concurrently rather than sequentially

390

4. **Resource Cleanup**: Always close the client or use context managers

391

5. **Error Handling**: Implement proper retry logic for transient failures

392

393

The async client is particularly beneficial when:

394

- Processing large numbers of events or impacts

395

- Integrating with async web frameworks (FastAPI, aiohttp)

396

- Building real-time monitoring systems

397

- Implementing concurrent data processing pipelines