c108.network
Utilities for estimating network transfer timeouts and durations.
This module provides tools for calculating safe timeout values and estimating transfer durations for network file transfers, including support for batch operations, retry strategies, and configurable transfer types.
BASE_TIMEOUT_SEC = 5.0
module-attribute
MAX_TIMEOUT_SEC = 3600.0
module-attribute
MIN_TIMEOUT_SEC = 10.0
module-attribute
OVERHEAD_PERCENT = 15.0
module-attribute
PROTOCOL_OVERHEAD_SEC = 2.0
module-attribute
SAFETY_MULTIPLIER = 2.0
module-attribute
SPEED_MBPS = 100.0
module-attribute
TransferOptions
dataclass
Configuration options for data transfer timing and performance factors.
Attributes:
| Name | Type | Description |
|---|---|---|
base_timeout |
float
|
Time limit for DNS resolution and connection establishment in seconds. |
max_retries |
int
|
Maximum number of retry attempts. Default is 3 retries (4 total attempts) - standard for handling transient failures. |
max_timeout |
float
|
Maximum allowed timeout duration in seconds. |
min_timeout |
float
|
Minimum allowable timeout duration in seconds to ensure practical network operations . |
overhead_percent |
float
|
Percentage of additional time for TCP/IP overhead such as headers and retransmissions. |
protocol_overhead |
float
|
Time overhead in seconds introduced by HTTP headers and chunked encoding. |
retry_delay |
int | float
|
Base retry delay in seconds. |
retry_multiplier |
int | float
|
Multiplier for exponential backoff. Default 2.0 multiplier, results in delays of: 1s, 2s, 4s, 8s, etc. |
safety_multiplier |
float
|
Multiplier to account for network variability and congestion buffer. |
speed |
float
|
Network speed in megabits per second. |
Source code in c108/network.py
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 | |
api_upload()
classmethod
API upload transfers - datacenter to cloud service.
Optimized for uploading to REST APIs, ML model registries (HuggingFace, MLflow), cloud storage APIs. Assumes asymmetric connection where upload is typically 1/5 to 1/10 of download speed.
Use for: Model uploads, dataset publishing, CI/CD artifact uploads.
Source code in c108/network.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | |
cdn_download()
classmethod
CDN download transfers - highly optimized delivery.
For downloading from CDNs (CloudFront, Cloudflare, Fastly). Use when downloading Python packages, pre-trained models, datasets from public repositories.
CDNs are geographically distributed and highly optimized.
Source code in c108/network.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
cloud_storage()
classmethod
Cloud storage transfers - AWS S3, GCP Cloud Storage, Azure Blob.
Regional cloud storage within same region/zone. Use for ML training data loading, checkpoint storage, artifact storage.
Assumes same-region transfer for best performance.
Source code in c108/network.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
fiber_symmetric(speed=800.0)
classmethod
Symmetric fiber with configurable bandwidth tier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
speed
|
float
|
Provisioned fiber speed in Mbps (accounts for ~20% overhead). Common tiers: - 80: 100 Mbps fiber - 400: 500 Mbps fiber - 800: 1 Gbps fiber (default) - 4000: 5 Gbps fiber - 9000: 10 Gbps fiber |
800.0
|
Example
Standard gigabit fiber
opts = TransferOptions.fiber_symmetric()
Enterprise 10 Gbps
opts = TransferOptions.fiber_symmetric(speed=9000.0)
Source code in c108/network.py
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 | |
ipfs_gateway()
classmethod
IPFS gateway transfers - content-addressed distributed storage.
For accessing datasets and models via IPFS gateways. IPFS is increasingly used in ML reproducibility, decentralized datasets (e.g., HuggingFace datasets on IPFS), and blockchain ML applications.
Gateway performance varies significantly by provider and content popularity. This preset assumes public gateways (pinata.cloud, ipfs.io, etc).
Use for: Decentralized datasets, immutable model versioning, Web3 ML.
Source code in c108/network.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
lan_sync(speed=600.0)
classmethod
Local network sync - Resilio Sync, Syncthing, LAN transfers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
speed
|
float
|
LAN speed in Mbps based on your network hardware. Common values: - 100: Fast Ethernet (100BASE-T) - 600: Gigabit Ethernet with realistic overhead (default) - 2500: 2.5 GbE - 5000: 5 GbE - 9000: 10 GbE with overhead |
600.0
|
Example
Default gigabit LAN
opts = TransferOptions.lan_sync()
10 GbE datacenter LAN
opts = TransferOptions.lan_sync(speed=9000.0)
Legacy 100 Mbps network
opts = TransferOptions.lan_sync(speed=100.0)
Source code in c108/network.py
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 | |
merge(*, base_timeout=None, max_retries=None, max_timeout=None, min_timeout=None, overhead_percent=None, protocol_overhead=None, retry_delay=None, retry_multiplier=None, safety_multiplier=None, speed=None)
Create a new TransferOptions instance with selectively updated fields.
If a parameter is None, no update is applied to the corresponding field.
Private fields (starting with '_') are excluded
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_timeout
|
int | float
|
Base Timeout |
None
|
max_retries
|
int
|
Max Retries |
None
|
max_timeout
|
int | float
|
Max Timeout |
None
|
min_timeout
|
int | float
|
Min Timeout |
None
|
overhead_percent
|
int | float
|
Overhead Percent |
None
|
protocol_overhead
|
int | float
|
Protocol Overhead |
None
|
retry_delay
|
int | float
|
Retry Delay |
None
|
retry_multiplier
|
int | float
|
Retry Multiplier |
None
|
safety_multiplier
|
int | float
|
Safety Multiplier |
None
|
speed
|
int | float
|
Speed |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
New TransferOptions instance with merged configuration |
Source code in c108/network.py
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 | |
mobile_4g()
classmethod
4G/LTE mobile networks - still dominant globally through 2030s.
Conservative settings for typical 4G performance across urban and suburban areas worldwide. Suitable for mobile app development, field data collection, and IoT applications.
Typical speeds: 15-50 Mbps in real-world conditions; use .merge(speed=X) if you measured your connection.
Source code in c108/network.py
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | |
mobile_5g()
classmethod
5G mobile networks - rapidly expanding in major cities globally.
Optimized for modern 5G in urban areas across US, Europe, and major Asian cities (Seoul, Singapore, Tokyo, etc.). Suitable for ML model downloads, real-time data streaming, and high-bandwidth mobile apps.
Typical speeds: 100-350 Mbps in real-world conditions; use .merge(speed=X) if you measured your connection.
Source code in c108/network.py
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
peer_transfer()
classmethod
Peer-to-peer direct transfers - assumes slower peer bottleneck.
Direct transfers between development machines, lab computers, or distributed training nodes. Assumes residential/office networks where one peer is the bottleneck.
Use for: Git LFS, local model sharing, distributed training setup.
Source code in c108/network.py
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | |
satellite_geo()
classmethod
Legacy GEO satellite internet (HughesNet, Viasat traditional service).
Geostationary satellites at 35,786 km altitude. High latency makes these less suitable for modern development but still common in remote areas. Use only when LEO satellites unavailable.
Typical speeds: 12-100 Mbps, Latency: 600-700ms.
Source code in c108/network.py
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | |
satellite_leo()
classmethod
Modern LEO satellite internet (Starlink, OneWeb, etc.).
Low Earth Orbit satellites provide near-broadband speeds with reasonable latency. Suitable for remote work, ML training in field deployments, and connecting edge computing in remote locations.
Typical speeds: 50-200 Mbps, Latency: 20-50ms.
Source code in c108/network.py
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | |
torrent_swarm()
classmethod
BitTorrent/P2P swarm transfers - multiple peer sources.
Optimized for torrent-based downloads where multiple peers contribute chunks simultaneously. Common for large dataset distribution, Linux ISO downloads, and decentralized model weight sharing.
Speed scales with swarm health (number of seeders). This preset assumes a healthy swarm (10+ seeders); use .merge(speed=X) based on observed swarm health.
Use for: Academic datasets, distro images, public model mirrors.
Source code in c108/network.py
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | |
TransferType
Bases: str, Enum
Predefined network transfer types.
Source code in c108/network.py
457 458 459 460 461 462 463 464 465 466 467 | |
batch_timeout(files, parallel=False, max_parallel=4, speed=100, speed_unit='mbps', **kwargs)
Estimate timeout for transferring multiple files.
For sequential transfers, timeouts are summed.
For parallel transfers, bandwidth is shared equally among concurrent transfers (up to max_parallel), and the total timeout is determined by the longest transfer.
Args: files: List of files to transfer. Each element can be: - str/PathLike: file path - int: file size in bytes - tuple: (file_path, file_size) for pre-computed sizes parallel: If True, assumes parallel transfer. If False, sequential. max_parallel: Maximum number of parallel transfers. Only used if parallel=True. speed: Expected transfer speed (divided among parallel transfers). speed_unit: Unit of speed: "mbps" (megabits/sec), "MBps" (megabytes/sec), "kbps" (kilobits/sec), "KBps" (kilobytes/sec), "gbps" (gigabits/sec). **kwargs: Additional parameters passed to transfer_timeout() (e.g., base_timeout, protocol_overhead, safety_multiplier).
Returns: Total estimated timeout in seconds as an integer.
Raises: ValueError: If the file list is empty or contains invalid elements.
Examples: >>> # Sequential and parallel upload of 3 equal-size files, # MB total >>> files = [220, 220, 2**20] # 1 MB each file >>> # OR files = ["file1.txt", "file2.txt", "file3.txt"] >>> batch_timeout(files, parallel=False) 30 >>> batch_timeout(files, parallel=True, max_parallel=3) 10
>>> # Sequential and parallel upload of 3 files of different sizes,
>>> # smaller files consume bandwidth inefficiently
>>> files = [1024, 2**20, 2**30] # bytes
>>> batch_timeout(files, parallel=False)
216
>>> batch_timeout(files, parallel=True, max_parallel=3)
573
>>> # Parallel upload of 3 large files estimates to same timeout
>>> files = [2**30, 2**30, 2**30] # bytes
>>> batch_timeout(files, parallel=True, max_parallel=3)
573
Source code in c108/network.py
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 | |
chunk_timeout(chunk_size, speed=100, speed_unit='mbps', **kwargs)
Estimate timeout for a single chunk in chunked/resumable transfer.
Useful for multipart uploads, streaming, or resumable upload protocols where files are split into chunks.
This method uses transfer_timeout() with file as one chunk preset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk_size
|
int
|
Size of the chunk in bytes. Common sizes: 5MB (S3 minimum), 8MB (typical), 16MB, 32MB, 64MB (large chunks). |
required |
speed
|
float
|
Expected transfer speed. |
100
|
speed_unit
|
Literal['mbps', 'MBps', 'kbps', 'KBps', 'gbps']
|
Unit of speed: "mbps" (megabits/sec), "MBps" (megabytes/sec), "kbps" (kilobits/sec), "KBps" (kilobytes/sec), "gbps" (gigabits/sec). |
'mbps'
|
**kwargs
|
Additional parameters passed to transfer_timeout(). |
{}
|
Returns:
| Type | Description |
|---|---|
int
|
Timeout for this chunk in seconds as an integer. |
Examples:
>>> # Timeout for 8MB chunk (typical chunk size)
>>> chunk_timeout(8*1024*1024, speed=100.0)
10
>>> # S3 multipart upload minimum chunk
>>> chunk_timeout(5*1024*1024, speed=12.0)
15
>>> # Large chunk for fast connection
>>> chunk_timeout(120*1024*1024, speed=500.0)
12
Source code in c108/network.py
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 619 620 621 | |
transfer_estimates(file_path=None, file_size=None, speed=100, speed_unit='mbps', **kwargs)
Get comprehensive transfer estimates with multiple metrics.
Returns a dictionary with timeout, transfer time, and formatted human-readable strings. Useful for displaying transfer information to users.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | PathLike[str] | None
|
Path to the file to be transferred. |
None
|
file_size
|
int | None
|
Size of the file in bytes. |
None
|
speed
|
float
|
Expected transfer speed. |
100
|
speed_unit
|
Literal['mbps', 'MBps', 'kbps', 'KBps', 'gbps']
|
Unit of speed: "mbps" (megabits/sec), "MBps" (megabytes/sec), "kbps" (kilobits/sec), "KBps" (kilobytes/sec), "gbps" (gigabits/sec). |
'mbps'
|
**kwargs
|
Additional parameters for transfer_timeout(). |
{}
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary containing: - file_size: Human-readable file size - file_size_bytes: File size in bytes - time: Human-readable duration string - time_sec: Expected duration in seconds (float) - timeout_sec: Timeout in seconds (int) - timeout: Human-readable timeout string - speed: Speed in Mbps |
Examples:
>>> # Get comprehensive estimate
>>> est = transfer_estimates(
... file_size=100*1024*1024,
... speed=50.0
... )
>>> {k: v for k, v in est.items() if k in ["file_size","time", "timeout"]}
{'file_size': '100.0 MB', 'time': '18.4 seconds', 'timeout': '44.0 seconds'}
Source code in c108/network.py
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 | |
transfer_speed(url, sample_size_kb=100, timeout_sec=10, num_samples=1)
Measure actual network transfer speed by downloading a sample from a URL.
This performs a real network test to measure achievable transfer speeds to a specific endpoint. Useful for determining appropriate speed_mbps values for timeout calculations.
WARNING: This makes actual HTTP requests and downloads data. Use responsibly and ensure you have permission to access the test URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to download from for speed testing. Should be a reliable endpoint that serves content quickly. Consider using a CDN-hosted file or a dedicated speed test endpoint. |
required |
sample_size_kb
|
int
|
Amount of data to download in kilobytes for each sample. Default is 100 KB - large enough for accuracy, small enough to be quick. Larger values give more accurate results but take longer. |
100
|
timeout_sec
|
float
|
Timeout for the speed test request itself. Default is 10 seconds. |
10
|
num_samples
|
int
|
Number of samples to take. Results are averaged. Default is 1. Multiple samples can improve accuracy but take longer. |
1
|
Returns:
| Type | Description |
|---|---|
float
|
Measured transfer speed in Mbps (megabits per second). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If parameters are invalid. |
URLError
|
If the URL cannot be accessed. |
HTTPError
|
If the server returns an error status. |
TimeoutError
|
If the speed test exceeds timeout_sec. |
Examples:
>>> # Measure speed to a CDN
>>> speed = transfer_speed("https://cdn.example.com/test.dat")
>>> # Use measured speed for timeout estimation
>>> speed = transfer_speed("https://api.example.com/health")
>>> timeout = transfer_timeout(
... file_size=10*1024*1024,
... speed_mbps=speed
... )
>>> # More accurate measurement with multiple samples
>>> speed = transfer_speed(
... "https://cdn.example.com/test.dat",
... sample_size_kb=500,
... num_samples=3
... )
>>> # Quick test with small sample
>>> speed = transfer_speed(
... "https://cdn.example.com/test.dat",
... sample_size_kb=50,
... timeout_sec=5.0
... )
Note
- Results vary based on server load, network conditions, and routing
- First request may be slower due to DNS resolution and connection setup
- Results represent download speed; upload speed may differ significantly
- Use multiple samples and test at different times for reliable estimates
- Consider using a dedicated speed test service for production applications
- This measures application-level throughput, not raw network capacity
Source code in c108/network.py
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 | |
transfer_time(file_path=None, file_size=None, speed=100, speed_unit='mbps', overhead_percent=OVERHEAD_PERCENT, unit='seconds')
Estimate the expected time for a file transfer (without safety margins).
Calculates realistic transfer time including network overhead, but without the safety multipliers and base timeouts used for timeout estimation. This is the "optimistic but realistic" estimate suitable for progress indicators, ETAs, and user-facing time estimates.
The calculation is based on the ideal transfer time plus a percentage for overhead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | PathLike[str] | None
|
Path to the file to be transferred. Either this or file_size must be provided. |
None
|
file_size
|
int | None
|
Size of the file in bytes. Either this or file_path must be provided. If both are given, file_size takes precedence. |
None
|
speed
|
float
|
Expected transfer speed in the specified unit. Default is 100.0 Mbps (~12.5 MB/s). |
100
|
speed_unit
|
Literal['mbps', 'MBps', 'kbps', 'KBps', 'gbps']
|
Unit of speed: "mbps" (megabits/sec), "MBps" (megabytes/sec), "kbps" (kilobits/sec), "KBps" (kilobytes/sec), "gbps" (gigabits/sec). |
'mbps'
|
overhead_percent
|
float
|
Additional time as percentage of transfer time to account for network protocol overhead. Default is 15.0% - represents realistic TCP/IP and HTTP overhead. |
OVERHEAD_PERCENT
|
unit
|
Literal['seconds', 'minutes', 'hours']
|
Unit for the returned duration. Options: "seconds", "minutes", "hours". Default is "seconds". |
'seconds'
|
Returns:
| Type | Description |
|---|---|
float
|
Estimated transfer time in the specified unit as a float. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither file_path nor file_size is provided, if speed is not positive, if file_size is negative, or if unit is invalid. |
FileNotFoundError
|
If file_path is provided but the file does not exist. |
OSError
|
If the file size cannot be determined. |
Examples:
>>> # Estimate transfer time for a 500MB file
>>> transfer_time(file_size=500*1024*1024, speed=100.0)
46.0
>>> # Get estimate in minutes for large file
>>> transfer_time(
... file_size=5*1024**3, # 5 GB
... speed=1024,
... unit="seconds"
... )
46.0
>>> # Using MB/s instead of Mbps
>>> transfer_time(
... file_size=5*1024**3, # 5 GB
... speed=1024,
... speed_unit="MBps",
... unit="seconds"
... )
5.75
>>> # Estimate in hours for very large transfer
>>> transfer_time(
... file_size=100*1024**3, # 100 GB
... speed=100.0,
... unit="hours"
... )
2.6168888888888886
Note
This estimates expected transfer time without safety margins. For setting timeouts, use transfer_timeout() instead which includes appropriate buffers for network variability, connection establishment, and safety margins.
This function is ideal for: - Progress bar ETAs - User-facing time estimates - Calculating average transfer speeds - Comparing different transfer types
Source code in c108/network.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 | |
transfer_timeout(file_path=None, file_size=None, speed=100, speed_unit='mbps', max_retries=None, retry_delay=None, opts=None)
Estimate a safe timeout value for transferring a file over a network.
Calculates transfer time based on file size and network conditions, accounting for protocol overhead, connection latency, and network variability. The timeout is calculated as:
timeout = base_timeout + protocol_overhead +
(transfer_time * (1 + overhead%) * safety_multiplier)
The result is then clamped to [min_timeout, max_timeout] and rounded up to the nearest integer using math.ceil() to ensure sufficient time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | PathLike[str] | None
|
Path to the file to be transferred. Either this or file_size must be provided. |
None
|
file_size
|
int | None
|
Size of the file in bytes. Either this or file_path must be provided. If both are given, file_size takes precedence. |
None
|
speed
|
int | float
|
Expected transfer speed in the specified unit. Default is 100.0 Mbps (~12.5 MB/s) - typical broadband connection. Common values: 10-50 (slow), 100-300 (typical), 500+ (fast). |
100
|
speed_unit
|
Literal['mbps', 'MBps', 'kbps', 'KBps', 'gbps']
|
Unit of speed: "mbps" (megabits/sec), "MBps" (megabytes/sec), "kbps" (kilobits/sec), "KBps" (kilobytes/sec), "gbps" (gigabits/sec). |
'mbps'
|
base_timeout
|
Base timeout added to all transfers regardless of size. Default is 5.0 seconds - accounts for DNS resolution (~1s), TCP handshake (~1s), TLS handshake (~1-2s), and HTTP request/response (~1s). |
required | |
overhead_percent
|
Additional time as percentage of transfer time to account for network protocol overhead. Default is 15.0% - represents TCP/IP headers (~5%), acknowledgments (~3%), potential retransmissions (~5%), and HTTP chunking (~2%). |
required | |
safety_multiplier
|
Multiplier applied to the calculated transfer time to provide a safety margin. Default is 2.0x - provides buffer for network congestion, routing changes, server load, and other variability. |
required | |
protocol_overhead
|
Fixed overhead for protocol-specific operations. Default is 2.0 seconds - for multipart boundaries, chunked encoding, and initial API processing. Use 5-10s for heavy API processing, 1-2s for simple file transfers. |
required | |
min_timeout
|
Absolute minimum timeout value to return. Default is 10.0 seconds - minimum practical timeout for any network operation considering connection establishment and basic handshakes. |
required | |
max_timeout
|
Maximum timeout value to return. Default is 3600.0 seconds (1 hour) - matches common API gateway limits (AWS ALB, CloudFlare, etc.). Set to None for no maximum. |
required | |
max_retries
|
int
|
Maximum number of retry attempts. Default is 3 retries (4 total attempts) - standard for handling transient failures. |
None
|
retry_delay
|
int | float
|
Initial backoff delay in seconds. Default is 1.0 second. |
None
|
retry_multiplier
|
Multiplier for exponential backoff. Default is 2.0, giving delays of: 1s, 2s, 4s, 8s, etc. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Estimated timeout in seconds as an integer (rounded up using math.ceil). |
int
|
The timeout is always clamped between min_timeout and max_timeout. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither file_path nor file_size is provided, if speed is not positive, if file_size is negative, or if min_timeout exceeds max_timeout. |
FileNotFoundError
|
If file_path is provided but the file does not exist. |
OSError
|
If the file size cannot be determined due to permissions or I/O error. |
Examples:
>>> # Small file on typical connection - returns minimum timeout
>>> transfer_timeout(file_size=1024) # 1 KB
10
>>> # 100MB file on slow connection
>>> transfer_timeout(file_size=100*1024*1024, speed=10.0)
191
>>> # Using megabytes per second instead of megabits
>>> transfer_timeout(
... file_size=500*1024*1024, # 500 MB
... speed=10.0, # 10 MB/s
... speed_unit="MBps"
... )
122
>>> # Large file with custom safety margin
>>> transfer_timeout(
... file_size=5*1024**3, # 5 GB
... speed=500.0,
... opts = TransferOptions(
... safety_multiplier=1.5, # Less conservative
... max_timeout=7200 # 2 hour max
... )
... )
149
>>> # Using file path
>>> transfer_timeout("backup.tar.gz", speed=50.0)
>>> # Conservative estimate for unreliable network
>>> transfer_timeout(
... file_size=1024*1024*1024, # 1 GB
... speed=50.0,
... opts=TransferOptions(overhead_percent=25.0,
... safety_multiplier=2.5)
... )
519
Note
This provides an estimate based on idealized conditions. Actual transfer times vary based on network congestion, server load, connection stability, routing, and many other factors. Always test with real-world conditions and adjust parameters accordingly.
For production use, consider: - API uploads: Use higher protocol_overhead (5-10s) and safety_multiplier (2.5-3.0) - Direct transfers: Lower protocol_overhead (1-2s) and safety_multiplier (1.5-2.0) - Mobile networks: Much higher safety_multiplier (3-4x) and overhead_percent (25-40%) - Batch uploads: Use batch_timeout() for better accuracy
Source code in c108/network.py
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 | |