This repository was archived by the owner on Apr 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathformatting_helpers.py
More file actions
618 lines (531 loc) · 19.5 KB
/
formatting_helpers.py
File metadata and controls
618 lines (531 loc) · 19.5 KB
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# Copyright 2023 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.
"""Shared helper functions for formatting jobs related info."""
from __future__ import annotations
import datetime
import html
import random
from typing import Any, Optional, Type, TYPE_CHECKING, Union
import bigframes_vendored.constants as constants
import google.api_core.exceptions as api_core_exceptions
import google.cloud.bigquery as bigquery
import humanize
if TYPE_CHECKING:
from IPython import display
import bigframes.core.events
GenericJob = Union[
bigquery.LoadJob, bigquery.ExtractJob, bigquery.QueryJob, bigquery.CopyJob
]
query_job_prop_pairs = {
"Job Id": "job_id",
"Destination Table": "destination",
"Slot Time": "slot_millis",
"Bytes Processed": "total_bytes_processed",
"Cache hit": "cache_hit",
}
def add_feedback_link(
exception: Union[
api_core_exceptions.RetryError, api_core_exceptions.GoogleAPICallError
]
):
exception.message = exception.message + f" {constants.FEEDBACK_LINK}"
def create_exception_with_feedback_link(
exception: Type[Exception],
arg: str = "",
):
if arg:
return exception(arg + f" {constants.FEEDBACK_LINK}")
return exception(constants.FEEDBACK_LINK)
def repr_query_job(query_job: Optional[bigquery.QueryJob]):
"""Return query job as a formatted string.
Args:
query_job:
The job representing the execution of the query on the server.
Returns:
Formatted string.
"""
if query_job is None:
return "No job information available"
if query_job.dry_run:
return f"Computation deferred. Computation will process {get_formatted_bytes(query_job.total_bytes_processed)}"
res = "Query Job Info"
for key, value in query_job_prop_pairs.items():
job_val = getattr(query_job, value)
if job_val is not None:
res += "\n"
if key == "Job Id": # add link to job
res += f"""Job url: {get_job_url(
project_id=query_job.project,
location=query_job.location,
job_id=query_job.job_id,
)}"""
elif key == "Slot Time":
res += f"""{key}: {get_formatted_time(job_val)}"""
elif key == "Bytes Processed":
res += f"""{key}: {get_formatted_bytes(job_val)}"""
else:
res += f"""{key}: {job_val}"""
return res
def repr_query_job_html(query_job: Optional[bigquery.QueryJob]):
"""Return query job as a formatted html string.
Args:
query_job:
The job representing the execution of the query on the server.
Returns:
Html string.
"""
if query_job is None:
return "No job information available"
if query_job.dry_run:
return f"Computation deferred. Computation will process {get_formatted_bytes(query_job.total_bytes_processed)}"
# We can reuse the plaintext repr for now or make a nicer table.
# For deferred mode consistency, let's just wrap the text in a pre block or similar,
# but the request implies we want a distinct HTML representation if possible.
# However, existing repr_query_job returns a simple string.
# Let's format it as a simple table or list.
res = "<h3>Query Job Info</h3><ul>"
for key, value in query_job_prop_pairs.items():
job_val = getattr(query_job, value)
if job_val is not None:
if key == "Job Id": # add link to job
url = get_job_url(
project_id=query_job.project,
location=query_job.location,
job_id=query_job.job_id,
)
res += f'<li>Job: <a target="_blank" href="{url}">{query_job.job_id}</a></li>'
elif key == "Slot Time":
res += f"<li>{key}: {get_formatted_time(job_val)}</li>"
elif key == "Bytes Processed":
res += f"<li>{key}: {get_formatted_bytes(job_val)}</li>"
else:
res += f"<li>{key}: {job_val}</li>"
res += "</ul>"
return res
current_display: Optional[display.HTML] = None
current_display_id: Optional[str] = None
previous_display_html: str = ""
def progress_callback(
event: bigframes.core.events.Event,
):
"""Displays a progress bar while the query is running"""
global current_display, current_display_id, previous_display_html
try:
import bigframes._config
import bigframes.core.events
except ImportError:
# Since this gets called from __del__, skip if the import fails to avoid
# ImportError: sys.meta_path is None, Python is likely shutting down.
# This will allow cleanup to continue.
return
progress_bar = bigframes._config.options.display.progress_bar
if progress_bar == "auto":
progress_bar = "notebook" if in_ipython() else "terminal"
if progress_bar == "notebook":
import IPython.display as display
if (
isinstance(event, bigframes.core.events.ExecutionStarted)
or current_display is None
or current_display_id is None
):
previous_display_html = ""
current_display_id = str(random.random())
current_display = display.HTML("Starting.")
display.display(
current_display,
display_id=current_display_id,
)
if isinstance(event, bigframes.core.events.BigQuerySentEvent):
previous_display_html = render_bqquery_sent_event_html(event)
display.update_display(
display.HTML(previous_display_html),
display_id=current_display_id,
)
elif isinstance(event, bigframes.core.events.BigQueryRetryEvent):
previous_display_html = render_bqquery_retry_event_html(event)
display.update_display(
display.HTML(previous_display_html),
display_id=current_display_id,
)
elif isinstance(event, bigframes.core.events.BigQueryReceivedEvent):
previous_display_html = render_bqquery_received_event_html(event)
display.update_display(
display.HTML(previous_display_html),
display_id=current_display_id,
)
elif isinstance(event, bigframes.core.events.BigQueryFinishedEvent):
previous_display_html = render_bqquery_finished_event_html(event)
display.update_display(
display.HTML(previous_display_html),
display_id=current_display_id,
)
elif isinstance(event, bigframes.core.events.ExecutionFinished):
display.update_display(
display.HTML(f"✅ Completed. {previous_display_html}"),
display_id=current_display_id,
)
elif isinstance(event, bigframes.core.events.SessionClosed):
display.update_display(
display.HTML(f"Session {event.session_id} closed."),
display_id=current_display_id,
)
elif progress_bar == "terminal":
if isinstance(event, bigframes.core.events.ExecutionStarted):
print("Starting execution.")
elif isinstance(event, bigframes.core.events.BigQuerySentEvent):
message = render_bqquery_sent_event_plaintext(event)
print(message)
elif isinstance(event, bigframes.core.events.BigQueryRetryEvent):
message = render_bqquery_retry_event_plaintext(event)
print(message)
elif isinstance(event, bigframes.core.events.BigQueryReceivedEvent):
message = render_bqquery_received_event_plaintext(event)
print(message)
elif isinstance(event, bigframes.core.events.BigQueryFinishedEvent):
message = render_bqquery_finished_event_plaintext(event)
print(message)
elif isinstance(event, bigframes.core.events.ExecutionFinished):
print("Execution done.")
def wait_for_job(job: GenericJob, progress_bar: Optional[str] = None):
"""Waits for job results. Displays a progress bar while the job is running
Args:
job (GenericJob):
The bigquery job to be executed.
progress_bar (str, Optional):
Which progress bar to show.
"""
if progress_bar == "auto":
progress_bar = "notebook" if in_ipython() else "terminal"
try:
if progress_bar == "notebook":
import IPython.display as display
display_id = str(random.random())
loading_bar = display.HTML(get_base_job_loading_html(job))
display.display(loading_bar, display_id=display_id)
job.result()
job.reload()
display.update_display(
display.HTML(get_base_job_loading_html(job)), display_id=display_id
)
elif progress_bar == "terminal":
inital_loading_bar = get_base_job_loading_string(job)
print(inital_loading_bar)
job.result()
job.reload()
if get_base_job_loading_string != inital_loading_bar:
print(get_base_job_loading_string(job))
else:
# No progress bar.
job.result()
job.reload()
except api_core_exceptions.RetryError as exc:
add_feedback_link(exc)
raise
except api_core_exceptions.GoogleAPICallError as exc:
add_feedback_link(exc)
raise
except KeyboardInterrupt:
job.cancel()
print(
f"Requested cancellation for {job.job_type.capitalize()}"
f" job {job.job_id} in location {job.location}..."
)
# begin the cancel request before immediately rethrowing
raise
def render_query_references(
*,
project_id: Optional[str],
location: Optional[str],
job_id: Optional[str],
request_id: Optional[str],
) -> str:
query_id = ""
if request_id and not job_id:
query_id = f" with request ID {project_id}:{location}.{request_id}"
return query_id
def render_job_link_html(
*,
project_id: Optional[str],
location: Optional[str],
job_id: Optional[str],
) -> str:
job_url = get_job_url(
project_id=project_id,
location=location,
job_id=job_id,
)
if job_url:
job_link = f' [<a target="_blank" href="{job_url}">Job {project_id}:{location}.{job_id} details</a>]'
else:
job_link = ""
return job_link
def render_job_link_plaintext(
*,
project_id: Optional[str],
location: Optional[str],
job_id: Optional[str],
) -> str:
job_url = get_job_url(
project_id=project_id,
location=location,
job_id=job_id,
)
if job_url:
job_link = f" Job {project_id}:{location}.{job_id} details: {job_url}"
else:
job_link = ""
return job_link
def get_job_url(
*,
project_id: Optional[str],
location: Optional[str],
job_id: Optional[str],
):
"""Return url to the query job in cloud console.
Returns:
String url.
"""
if project_id is None or location is None or job_id is None:
return None
return f"""https://console.cloud.google.com/bigquery?project={project_id}&j=bq:{location}:{job_id}&page=queryresults"""
def render_bqquery_sent_event_html(
event: bigframes.core.events.BigQuerySentEvent,
) -> str:
"""Return progress bar html string
Args:
query_job (bigquery.QueryJob):
The job representing the execution of the query on the server.
Returns:
Html string.
"""
job_link = render_job_link_html(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
)
query_id = render_query_references(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
request_id=event.request_id,
)
query_text_details = f"<details><summary>SQL</summary><pre>{html.escape(event.query)}</pre></details>"
return f"""
Query started{query_id}.{job_link}{query_text_details}
"""
def render_bqquery_sent_event_plaintext(
event: bigframes.core.events.BigQuerySentEvent,
) -> str:
"""Return progress bar html string
Args:
query_job (bigquery.QueryJob):
The job representing the execution of the query on the server.
Returns:
Html string.
"""
job_link = render_job_link_plaintext(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
)
query_id = render_query_references(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
request_id=event.request_id,
)
return f"Query started{query_id}.{job_link}"
def render_bqquery_retry_event_html(
event: bigframes.core.events.BigQueryRetryEvent,
) -> str:
"""Return progress bar html string for retry event."""
job_link = render_job_link_html(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
)
query_id = render_query_references(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
request_id=event.request_id,
)
query_text_details = f"<details><summary>SQL</summary><pre>{html.escape(event.query)}</pre></details>"
return f"""
Retrying query{query_id}.{job_link}{query_text_details}
"""
def render_bqquery_retry_event_plaintext(
event: bigframes.core.events.BigQueryRetryEvent,
) -> str:
"""Return progress bar plaintext string for retry event."""
job_link = render_job_link_plaintext(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
)
query_id = render_query_references(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
request_id=event.request_id,
)
return f"Retrying query{query_id}.{job_link}"
def render_bqquery_received_event_html(
event: bigframes.core.events.BigQueryReceivedEvent,
) -> str:
"""Return progress bar html string for received event."""
job_link = render_job_link_html(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
)
query_id = render_query_references(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
request_id=None,
)
query_plan_details = ""
if event.query_plan:
plan_str = "\n".join([str(entry) for entry in event.query_plan])
query_plan_details = f"<details><summary>Query Plan</summary><pre>{html.escape(plan_str)}</pre></details>"
return f"""
Query{query_id} is {event.state}.{job_link}{query_plan_details}
"""
def render_bqquery_received_event_plaintext(
event: bigframes.core.events.BigQueryReceivedEvent,
) -> str:
"""Return progress bar plaintext string for received event."""
job_link = render_job_link_plaintext(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
)
query_id = render_query_references(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
request_id=None,
)
return f"Query{query_id} is {event.state}.{job_link}"
def render_bqquery_finished_event_html(
event: bigframes.core.events.BigQueryFinishedEvent,
) -> str:
"""Return progress bar html string for finished event."""
bytes_str = ""
if event.total_bytes_processed is not None:
bytes_str = f" {humanize.naturalsize(event.total_bytes_processed)}"
slot_time_str = ""
if event.slot_millis is not None:
slot_time = datetime.timedelta(milliseconds=event.slot_millis)
slot_time_str = f" in {humanize.naturaldelta(slot_time)} of slot time"
job_link = render_job_link_html(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
)
query_id = render_query_references(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
request_id=None,
)
return f"""
Query processed{bytes_str}{slot_time_str}{query_id}.{job_link}
"""
def render_bqquery_finished_event_plaintext(
event: bigframes.core.events.BigQueryFinishedEvent,
) -> str:
"""Return progress bar plaintext string for finished event."""
bytes_str = ""
if event.total_bytes_processed is not None:
bytes_str = f" {humanize.naturalsize(event.total_bytes_processed)} processed."
slot_time_str = ""
if event.slot_millis is not None:
slot_time = datetime.timedelta(milliseconds=event.slot_millis)
slot_time_str = f" Slot time: {humanize.naturaldelta(slot_time)}."
job_link = render_job_link_plaintext(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
)
query_id = render_query_references(
project_id=event.billing_project,
location=event.location,
job_id=event.job_id,
request_id=None,
)
return f"Query{query_id} finished.{bytes_str}{slot_time_str}{job_link}"
def get_base_job_loading_html(job: GenericJob):
"""Return progress bar html string
Args:
job (GenericJob):
The job representing the execution of the query on the server.
Returns:
Html string.
"""
return f"""{job.job_type.capitalize()} job {job.job_id} is {job.state}. <a target=\"_blank\" href="{get_job_url(
project_id=job.job_id,
location=job.location,
job_id=job.job_id,
)}">Open Job</a>"""
def get_base_job_loading_string(job: GenericJob):
"""Return progress bar string
Args:
job (GenericJob):
The job representing the execution of the query on the server.
Returns:
String
"""
return f"""{job.job_type.capitalize()} job {job.job_id} is {job.state}. \n{get_job_url(
project_id=job.job_id,
location=job.location,
job_id=job.job_id,
)}"""
def get_formatted_time(val):
"""Try to format time
Args:
val (Any):
Time in ms.
Returns:
Duration string
"""
try:
return humanize.naturaldelta(datetime.timedelta(milliseconds=float(val)))
except Exception:
return val
def get_formatted_bytes(val):
"""Try to format bytes
Args:
val (Any):
Bytes to format
Returns:
Duration string
"""
if isinstance(val, int):
return humanize.naturalsize(val)
return "N/A"
def get_bytes_processed_string(val: Any):
"""Try to get bytes processed string. Return empty if passed non int value"""
bytes_processed_string = ""
if isinstance(val, int):
bytes_processed_string = f"""{get_formatted_bytes(val)} processed. """
return bytes_processed_string
def in_ipython():
"""Return True iff we're in a colab-like IPython."""
try:
import IPython
except (ImportError, NameError):
return False
return hasattr(IPython.get_ipython(), "kernel")