Skip to content

File Storage API

Upload, download, search, and manage files in Silo file storage buckets. Requires FILE_TOKEN. Supports async bulk operations.

Bases: BaseAPIClient

API client for Silo file storage operations.

This class provides methods for managing files in the Authentic8 Silo platform, including uploading, downloading, searching, modifying, and deleting files.

The file storage API allows you to: - Upload files from local system to Silo storage - Download files from Silo storage to local system - Search for files using various criteria - Modify file properties and metadata - Delete files from storage - Manage file permissions and access controls

Examples:

>>> from silo_sdk import FileAPI, load_config
>>> config = load_config()
>>> files = FileAPI(config)
>>>
>>> # Upload a file
>>> result = files.upload_file(
...     bucket_id="my_bucket",
...     file_path="/path/to/local/file.pdf",
...     name="document.pdf",
...     path="/documents/"
... )
>>>
>>> # Search for files
>>> found_files = files.find_files(
...     bucket_id="my_bucket",
...     name="document.pdf",
...     path="/documents/"
... )
Source code in silo_sdk/storage/file_api.py
 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
 619
 620
 621
 622
 623
 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
 735
 736
 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
 830
 831
 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
 946
 947
 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
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
class FileAPI(BaseAPIClient):
    """API client for Silo file storage operations.

    This class provides methods for managing files in the Authentic8 Silo platform,
    including uploading, downloading, searching, modifying, and deleting files.

    The file storage API allows you to:
    - Upload files from local system to Silo storage
    - Download files from Silo storage to local system
    - Search for files using various criteria
    - Modify file properties and metadata
    - Delete files from storage
    - Manage file permissions and access controls

    Examples:
        >>> from silo_sdk import FileAPI, load_config
        >>> config = load_config()
        >>> files = FileAPI(config)
        >>>
        >>> # Upload a file
        >>> result = files.upload_file(
        ...     bucket_id="my_bucket",
        ...     file_path="/path/to/local/file.pdf",
        ...     name="document.pdf",
        ...     path="/documents/"
        ... )
        >>>
        >>> # Search for files
        >>> found_files = files.find_files(
        ...     bucket_id="my_bucket",
        ...     name="document.pdf",
        ...     path="/documents/"
        ... )
    """

    def __init__(self, config: dict[str, Any]) -> None:
        """Initialize the file storage API client.

        Args:
            config: Configuration dictionary containing API settings

        Raises:
            ConfigurationError: If required configuration is missing
        """
        super().__init__(config)

        # Validate required configuration
        validate_config_for_api(config, ["FILE_TOKEN"])

        self.auth_token = config["FILE_TOKEN"]
        self._config = config  # Store config for later use
        # Built once, not per download. create_ssl_context() parses the certifi
        # CA bundle off disk every call, so building it inside a request path
        # meant bulk_download_async re-parsed it once per file. Matches what
        # HarvesterAPI already does.
        self._ssl_context = self.create_ssl_context()
        self.logger.info("Initialized FileAPI client")

    @asynccontextmanager
    async def _client_scope(
        self, client: httpx.AsyncClient | None
    ) -> AsyncIterator[httpx.AsyncClient]:
        """Yield the caller's client, or a short-lived one owned by this call.

        Bulk operations pass a single client down so that one connection pool
        and one TLS handshake are shared across every file in the batch —
        creating a client per download meant a fresh handshake per file and
        threw away keep-alive entirely. A direct call to one of the download
        methods still gets a client of its own and closes it on the way out,
        so nothing about the public API changes.

        Args:
            client: A client to borrow, or ``None`` to create and own one.

        Yields:
            The client to issue requests on.
        """
        if client is not None:
            yield client
        else:
            async with httpx.AsyncClient(verify=self._ssl_context) as owned:
                yield owned

    def _cleanup_partial_file(self, output_path: Path) -> None:
        """Remove a partially-written file left behind by a failed download.

        Called when a download raises mid-stream (e.g. a dropped connection
        or disk error while writing chunks). The output file was already
        opened in write mode by that point, so any prior contents at
        ``output_path`` are gone regardless — leaving the truncated remnant
        in place would let a caller mistake it for a complete file.

        Args:
            output_path: Path of the file that was being written when the
                download failed.
        """
        try:
            if output_path.exists():
                output_path.unlink()
                self.logger.debug(
                    "Removed partial file after failed download: %s", output_path
                )
        except OSError as cleanup_error:
            self.logger.warning(
                "Failed to remove partial file %s after download error: %s",
                output_path,
                cleanup_error,
            )

    async def _prepare_output_dir_async(
        self, output_path: Path, create_dirs: bool
    ) -> None:
        """Create the destination's parent directory off the event loop.

        ``mkdir`` blocks like every other filesystem call in the async
        download paths, and it was the one left inline when the writes were
        offloaded -- so on a slow or network-mounted destination each
        concurrent download in a bulk run stalled the loop for the duration
        of its own directory creation, which is the stall those downloads
        run concurrently to avoid.

        Failures are wrapped rather than left bare: the callers turn every
        other filesystem error into ``FileAPIError``, and a caller catching
        that should not have to also catch ``OSError`` for the one operation
        that happens to run first.

        Args:
            output_path: Destination file path, whose parent is created.
            create_dirs: When false, does nothing.

        Raises:
            FileAPIError: If the directory cannot be created.
        """
        if not create_dirs or output_path.parent == output_path:
            return
        try:
            await asyncio.to_thread(
                output_path.parent.mkdir, parents=True, exist_ok=True
            )
        except OSError as e:
            raise FileAPIError(
                f"Failed to create output directory {output_path.parent}: {e}"
            ) from e

    @api_tag(MethodType.API_COMMAND, api_command="putfile")
    def upload_file(
        self,
        bucket_id: str,
        file_path: str | Path,
        name: str,
        path: str = "/",
        content_type: str | None = None,
    ) -> dict[str, Any]:
        """Upload file from local system to Silo storage.

        Uploads a file from the local filesystem to the specified bucket in
        Silo storage with the given name and path.

        Args:
            bucket_id: ID of the destination bucket (required)
            file_path: Path to the local file to upload (required)
            name: Name to give the file in Silo storage (required)
            path: Path in Silo storage to store the file (optional, defaults to "/")
            content_type: MIME content type of the file (optional, auto-detected if not provided)

        Returns:
            Dictionary with a single key, ``file_id`` -- the identifier of
            the newly created file record. The response body is returned
            verbatim.

        Warning:
            ``/putfile/`` returns **only** ``file_id``. An earlier version of
            this docstring also promised ``name``, ``path``, ``size``,
            ``content_type`` and ``upload_ts``; none of them are sent, and
            reading one raises ``KeyError``. To get the rest of the record,
            call :meth:`get_file_info` with the returned ``file_id``.

        Raises:
            FileAPIError: If file upload fails. For a non-2xx response the
                server's reason (e.g. "file already exists", "bad auth") is
                included in the message. Also raised, before anything is
                sent, for a ``name`` containing ``^``, ``%``, backslash or
                ``/``, or a ``path`` containing ``^``, ``%`` or backslash
                (the server always rejects these).
            ValidationError: If other parameters are invalid

        Examples:
            >>> result = api.upload_file(
            ...     bucket_id="documents",
            ...     file_path="/home/user/report.pdf",
            ...     name="quarterly_report.pdf",
            ...     path="/reports/2024/"
            ... )
            >>> print(f"Uploaded file ID: {result['file_id']}")
        """
        # Validate parameters
        if not bucket_id or not isinstance(bucket_id, str):
            raise ValidationError("Bucket ID must be a non-empty string")

        if not name or not isinstance(name, str):
            raise ValidationError("File name must be a non-empty string")

        if not isinstance(path, str):
            raise ValidationError("Path must be a string")

        # The server always rejects these characters; say so before uploading.
        # FileAPIError, not ValidationError: before 0.16.1 these reached the
        # server and came back as FileAPIError, and callers catch that.
        bad_name = [c for c in _BAD_NAME_CHARS if c in name]
        if bad_name:
            raise FileAPIError(
                f"File name must not contain any of {' '.join(_BAD_NAME_CHARS)} "
                f"(found {' '.join(bad_name)}); the server rejects them"
            )
        bad_path = [c for c in _BAD_PATH_CHARS if c in path]
        if bad_path:
            raise FileAPIError(
                f"Path must not contain any of {' '.join(_BAD_PATH_CHARS)} "
                f"(found {' '.join(bad_path)}); the server rejects them"
            )

        # Convert to Path object and validate file exists
        file_path = Path(file_path)
        if not file_path.exists():
            raise ValidationError(f"File does not exist: {file_path}")

        if not file_path.is_file():
            raise ValidationError(f"Path is not a file: {file_path}")

        # Auto-detect content type if not provided
        if content_type is None:
            import mimetypes

            content_type, _ = mimetypes.guess_type(str(file_path))
            if content_type is None:
                content_type = "application/octet-stream"

        # Prepare upload data for /putfile/ endpoint
        url = f"{self.base_url.rstrip('/')}/putfile/"

        try:
            self.logger.debug(
                "Uploading file: %s to bucket: %s", file_path.name, bucket_id
            )
            self.logger.debug("Upload URL: %s", url)

            with open(file_path, "rb") as f:
                # Prepare form data for /putfile/ endpoint
                data = {
                    "auth": self.auth_token,
                    "bucket_id": bucket_id,
                    "name": name,
                    "path": path,
                }

                # Add optional parameters
                if content_type:
                    data["content_type"] = content_type

                files = {"file": (file_path.name, f, content_type)}

                # Debug logging
                self.logger.debug("Data keys: %s", list(data.keys()))
                self.logger.debug("Files keys: %s", list(files.keys()))

                # Route through the shared session so retry/proxy/User-Agent
                # configuration from BaseAPIClient is honored. Override
                # Content-Type (set to None to drop the session's default
                # "application/json") so requests can compute the correct
                # multipart/form-data boundary itself.
                response = self.session.post(
                    url,
                    data=data,
                    files=files,
                    timeout=self.timeout,
                    headers={"Content-Type": None},
                )

                # Log response details for debugging
                self.logger.debug("Response status: %s", response.status_code)
                if not response.ok:
                    self.logger.error("Response content: %s", response.text)

                _raise_for_status(response, "upload file")

                result: dict[str, Any] = response.json()
                self.logger.info("Successfully uploaded file: %s", name)
                return result

        except Exception as e:
            if isinstance(e, FileAPIError):
                raise
            raise FileAPIError(f"Failed to upload file: {e}") from e

    @api_tag(MethodType.API_COMMAND, api_command="getfile")
    def download_file(
        self,
        file_id: str,
        output_path: str | Path,
        create_dirs: bool = True,
    ) -> str:
        """Download file by file_id from Silo storage.

        Downloads a file from Silo storage to the local filesystem using the
        file's unique identifier.

        Args:
            file_id: ID of the file to download
            output_path: Path where to save the downloaded file
            create_dirs: Whether to create parent directories if they don't exist

        Note:
            Wire endpoint: ``POST https://extapi.authentic8.com/getfile/`` with
            form-data fields ``id`` (file ID) and ``auth`` (file token). This is
            **not** a JSON command-array request — it uses a separate endpoint
            and multipart form-data, not the standard ``/api/`` command format.
            The response body is the raw file content (binary stream).

        Warning:
            The server reports a malware-blocked file as **HTTP 200** with a
            JSON body (``error``, ``malware``, ...) instead of the file. That
            is raised as ``FileAPIError`` and nothing is written. A body
            shorter than its ``Content-Length`` is also an error (on some
            files the server's Content-Length exceeds the body by exactly 28
            bytes -- a known server defect).

        Returns:
            Path of the downloaded file (as string)

        Raises:
            FileAPIError: If file download fails, the server blocks the file
                as malware, or the body is truncated. For a non-2xx response
                the server's reason (e.g. "file is folder", "file not found",
                "bad auth") is included in the message.
            ValidationError: If parameters are invalid

        Examples:
            >>> downloaded_path = api.download_file(
            ...     file_id="abc123",
            ...     output_path="/home/user/downloads/report.pdf"
            ... )
            >>> print(f"File downloaded to: {downloaded_path}")
        """
        if not file_id or not isinstance(file_id, str):
            raise ValidationError("File ID must be a non-empty string")

        if not output_path:
            raise ValidationError("Output path must be provided")

        # Convert to Path object and resolve to prevent path traversal
        output_path_raw = str(output_path)
        output_path = Path(output_path).resolve()

        # Warn if the original path contained traversal components
        if ".." in output_path_raw:
            self.logger.warning(
                "Output path contained '..' components, resolved to: %s",
                output_path,
            )

        # Create parent directories if requested
        if create_dirs and output_path.parent != output_path:
            output_path.parent.mkdir(parents=True, exist_ok=True)

        url = f"{self.base_url.rstrip('/')}/getfile/"

        try:
            self.logger.debug("Downloading file ID: %s", file_id)

            data = {
                "id": file_id,
                "auth": self.auth_token,
            }

            # Route through the shared session so retry/proxy/User-Agent
            # configuration from BaseAPIClient is honored. Override
            # Content-Type (set to None to drop the session's default
            # "application/json") so requests encodes the form body correctly.
            response = self.session.post(
                url,
                data=data,
                timeout=self.timeout,
                stream=True,
                headers={"Content-Type": None},
            )
            _raise_for_status(response, "download file")

            # A malware-blocked file comes back as HTTP 200 with a JSON
            # description instead of the file; never write that as content.
            if _is_json_response(response):
                blocked = _malware_error(response.content)
                if blocked is not None:
                    raise blocked

            expected = _expected_length(response)
            received = 0

            # Write file content
            try:
                with open(output_path, "wb") as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        if chunk:
                            f.write(chunk)
                            received += len(chunk)
                if expected is not None and received < expected:
                    raise _short_body_error(expected, received)
            except Exception:
                self._cleanup_partial_file(output_path)
                raise

            self.logger.info("Successfully downloaded file to: %s", output_path)
            return str(output_path)

        except Exception as e:
            if isinstance(e, FileAPIError):
                raise
            defect = _short_body_defect(e)
            if defect is not None:
                raise defect from e
            raise FileAPIError(f"Failed to download file: {e}") from e

    @api_tag(MethodType.API_COMMAND, api_command="findfiles")
    def find_files(
        self,
        bucket_id: str,
        name: str | None = None,
        path: str | None = None,
        file_type: str | None = None,
        created_before: str | None = None,
        created_after: str | None = None,
        size_min: int | None = None,
        size_max: int | None = None,
        limit: int | None = None,
        metadata_filters: dict[str, str] | None = None,
    ) -> list[dict[str, Any]]:
        """Search Silo storage for files by various criteria.

        Searches for files in the specified bucket by name, path, kind,
        creation date, and file size.

        Args:
            bucket_id: ID of the bucket to search in.
            name: File name to match. **Exact, case-insensitive match** --
                there are no wildcards (``"*"`` and ``"*.txt"`` match nothing).
            path: Folder to list. **Exact match, direct children only** -- not
                recursive, and no wildcards.
            file_type: Filter by kind: ``"file"`` or ``"directory"`` only. It
                is **not** a MIME type or extension filter
                (``"application/pdf"`` matches nothing). Sent as
                ``"type"`` in the wire format (field name differs from this
                parameter name).
            created_before: Search for files created before this date (ISO
                format). Sent as ``":created_before"`` in the wire format
                (note the colon prefix on the wire field name).
            created_after: Search for files created after this date (ISO
                format). Sent as ``":created_after"`` in the wire format
                (note the colon prefix on the wire field name).
            size_min: Minimum file size in bytes. **Applied here, not by the
                server** -- see ``limit`` below; the server's ``findfiles``
                allowlist has no size fields, so it silently ignores these.
                Records are matched on the wire field ``"file_size"``.
                Directories carry ``"file_size": null`` and are therefore
                excluded whenever either size bound is given.
            size_max: Maximum file size in bytes. Same handling as ``size_min``.
            limit: Maximum number of results to return. **Applied here, not by
                the server.** The value is still sent on the wire, but live
                testing shows the server returns the full listing regardless,
                so the list is truncated on arrival to keep the documented
                contract true. Expect no bandwidth saving from it.
            metadata_filters: **Has no effect.** The server ignores these
                and the SDK does not apply them, so the full listing is
                returned; a warning is emitted when supplied. Kept for
                signature compatibility.

        Note:
            Wire format parameter name differences:

            - Python ``file_type`` → wire ``"type"``
            - Python ``created_before`` → wire ``":created_before"`` (colon prefix)
            - Python ``created_after`` → wire ``":created_after"`` (colon prefix)

            Wire format structure::

                {
                    "command": "findfiles",
                    "bucket_id": "my_bucket",
                    "type": "file",                     # ← file_type → "type"
                    ":created_before": "2026-01-01",    # ← colon prefix
                    ":created_after": "2025-01-01"      # ← colon prefix
                }

        Returns:
            List of dictionaries, one per matching file. The result is passed
            through unfiltered, so a field the platform adds appears here
            without an SDK change. Fields returned:

            - ``bucket_id``: Bucket the file lives in
            - ``file_id``: Unique file identifier
            - ``name``: File name
            - ``path``: File path in storage
            - ``type``: File type
            - ``content_type``: MIME type
            - ``file_size``: File size in bytes
            - ``create_user_id``: ID of the account that created the file
            - ``create_username``: Name of the account that created the file
            - ``create_ts``: Creation timestamp (ISO-8601)
            - ``expire_ts``: Expiry timestamp (ISO-8601)
            - ``uploading_until``: Upload deadline (ISO-8601)
            - ``session_id``: Session that created the file. **Not always
                present** -- records created outside a browsing session omit
                it, so use ``.get("session_id")``.

            ``session_id`` lets you correlate a stored file with the session
            activity that produced it.

            The creating account is reported as **two** fields,
            ``create_user_id`` and ``create_username``. There is no
            ``create_user``; an earlier version of this list named one.

            **Directories are included in the listing**, carrying a
            ``content_type`` of ``Folder``. They are not downloadable —
            :meth:`download_file` and :meth:`bulk_download_async` get an API
            error for one — so filter them out before feeding these entries to
            a download.

        Raises:
            FileAPIError: If file search fails
            ValidationError: If parameters are invalid

        Examples:
            >>> files = api.find_files(
            ...     bucket_id="documents",
            ...     name="report.pdf",
            ...     path="/reports/",
            ...     created_after="2024-01-01T00:00:00Z",
            ...     size_min=1024,
            ...     limit=100
            ... )
            >>> for file in files:
            ...     print(f"{file['name']} - {file['file_size']} bytes")
        """
        if not bucket_id or not isinstance(bucket_id, str):
            raise ValidationError("Bucket ID must be a non-empty string")

        # Build search payload
        search_params: dict[str, Any] = {
            "command": "findfiles",
            "bucket_id": bucket_id,
        }

        # Add optional search criteria
        if name is not None:
            search_params["name"] = name

        if path is not None:
            search_params["path"] = path

        if file_type is not None:
            search_params["type"] = file_type

        if created_before is not None:
            search_params[":created_before"] = created_before

        if created_after is not None:
            search_params[":created_after"] = created_after

        if size_min is not None:
            if not isinstance(size_min, int) or size_min < 0:
                raise ValidationError("size_min must be a non-negative integer")
            search_params["size_min"] = size_min

        if size_max is not None:
            if not isinstance(size_max, int) or size_max < 0:
                raise ValidationError("size_max must be a non-negative integer")
            search_params["size_max"] = size_max

        if limit is not None:
            if not isinstance(limit, int) or limit <= 0:
                raise ValidationError("limit must be a positive integer")
            search_params["limit"] = limit

        if metadata_filters is not None:
            if not isinstance(metadata_filters, dict):
                raise ValidationError("metadata_filters must be a dictionary")
            # Add metadata filters to search parameters
            for key, value in metadata_filters.items():
                search_params[f"metadata:{key}"] = value
            if metadata_filters:
                self.logger.warning(_METADATA_FILTERS_NOTE)
                warnings.warn(_METADATA_FILTERS_NOTE, UserWarning, stacklevel=2)

        payload = [search_params]

        try:
            self.logger.debug("Searching for files in bucket: %s", bucket_id)
            response = self._make_api_request("POST", "api/", self.auth_token, payload)

            # Extract results
            if len(response) >= 2 and isinstance(response[1], dict):
                result_entry = response[1]
                if "error" in result_entry:
                    raise FileAPIError(f"API error: {result_entry['error']}")
                result = result_entry.get("result")
                # The error can also arrive nested inside the result. Returning
                # [] for it made a rejected search indistinguishable from an
                # empty bucket.
                if isinstance(result, dict) and result.get("error"):
                    raise FileAPIError(f"API error: {result['error']}")
                if isinstance(result, list):
                    if size_min is not None or size_max is not None:
                        # "size_min"/"size_max" are sent, but findfiles'
                        # server-side allowlist has no size fields, so they are
                        # dropped without error -- same shape as "limit" below.
                        # Filter here, before the limit slice: truncating first
                        # would return fewer than `limit` matches even when
                        # enough exist. Directories report "file_size": null
                        # and cannot satisfy a size bound, so they drop out.
                        unfiltered = len(result)
                        result = [
                            f
                            for f in result
                            if isinstance(f.get("file_size"), int)
                            and (size_min is None or f["file_size"] >= size_min)
                            and (size_max is None or f["file_size"] <= size_max)
                        ]
                        if len(result) != unfiltered:
                            self.logger.debug(
                                "Server returned %d results ignoring the size "
                                "bounds; %d match after client-side filtering",
                                unfiltered,
                                len(result),
                            )
                    self.logger.info("Found %d files matching criteria", len(result))
                    if limit is not None and len(result) > limit:
                        # The server accepts "limit" and ignores it -- a bucket
                        # of 109 answers limit=2 with all 109. Nothing here
                        # truncated either, so the documented cap was simply
                        # untrue and callers paging on it got the whole bucket.
                        # Enforcing it client-side costs one slice and makes
                        # the signature honest; it cannot save the transfer,
                        # which is why the docstring says so out loud.
                        self.logger.debug(
                            "Server returned %d results for limit=%d; "
                            "truncating client-side",
                            len(result),
                            limit,
                        )
                        return result[:limit]
                    return result

            # Only a list result is a listing; an empty bucket is {"result": []}.
            # Anything else is raised rather than passed off as "no files".
            rendered = self._format_response_for_log(response)
            self.logger.warning(
                "Unexpected response format for find_files: %s", rendered
            )
            raise FileAPIError(f"Unexpected response format: {rendered}")

        except Exception as e:
            if isinstance(e, FileAPIError):
                raise
            raise FileAPIError(f"Failed to search for files: {e}") from e

    @api_tag(MethodType.CONVENIENCE, wraps=["findfiles"])
    def list_files(
        self,
        bucket_id: str,
        limit: int | None = None,
    ) -> list[dict[str, Any]]:
        """List files in a bucket.

        Lists files in the specified bucket with optional limit.
        This is a convenience wrapper around find_files with no filters.

        Args:
            bucket_id: ID of the bucket to list files from
            limit: Maximum number of files to return. Enforced client-side —
                see :meth:`find_files` for why.

        Returns:
            List of dictionaries containing file information. Includes
            directories (``content_type`` of ``Folder``), which are not
            downloadable — filter before passing these to a download.

        Raises:
            FileAPIError: If file listing fails
            ValidationError: If parameters are invalid
        """
        return self.find_files(bucket_id=bucket_id, limit=limit)

    @api_tag(MethodType.API_COMMAND, api_command="modifyfile")
    def modify_file(
        self,
        file_id: str,
        name: str | None = None,
        expire_ts: str | int | float | None = None,
        path: str | None = None,
        content_type: str | None = None,
    ) -> dict[str, Any]:
        """Change properties of a file by file_id in Silo storage.

        Modifies various properties of an existing file including its name,
        path, expiration time, and content type.

        Args:
            file_id: ID of the file to modify (required)
            name: New name for the file (optional)
            expire_ts: New file expiry (optional). An ``int``/``float`` is
                sent as a string. Accepted forms:

                - epoch seconds, e.g. ``1767225600``
                - ``"now+SECONDS"`` -- that long from now, e.g. ``"now+3600"``
                - ``"+SECONDS"`` -- extend the **current** expiry by that
                  long; the server errors on a non-expiring file ("cannot
                  extend expire time for non-expiring file")
                - ``"reset"`` -- the bucket's default expiry; errors if the
                  bucket has none ("bucket has no expire time to reset to")
                - an ISO-8601 timestamp string
            path: Path of new location to move file (optional)
            content_type: New content type of modified file (optional)

        Returns:
            Dictionary containing the API response

        Raises:
            FileAPIError: If file modification fails, including a server
                rejection (top-level or nested ``error``)
            ValidationError: If parameters are invalid

        Examples:
            >>> updated_file = api.modify_file(
            ...     file_id="abc123",
            ...     name="updated_report.pdf",
            ...     expire_ts="now+3600",
            ...     path="/reports/2024/updated/"
            ... )
            >>> print(f"Updated file: {updated_file}")
        """
        if not file_id or not isinstance(file_id, str):
            raise ValidationError("File ID must be a non-empty string")

        # Build modifyfile command — setauth is injected by _make_api_request
        modify_command: dict[str, Any] = {"command": "modifyfile", "file_id": file_id}

        # Add optional parameters
        if name is not None:
            if not isinstance(name, str) or not name:
                raise ValidationError("Name must be a non-empty string")
            modify_command["name"] = name

        if expire_ts is not None:
            if isinstance(expire_ts, bool):
                # FileAPIError: a bool used to reach the server and fail there.
                raise FileAPIError("expire_ts must be a string or a number")
            # The server calls .startswith() on it, so a bare number is an
            # HTTP 500 there.
            if isinstance(expire_ts, (int, float)):
                expire_ts = str(expire_ts)
            modify_command["expire_ts"] = expire_ts

        if path is not None:
            if not isinstance(path, str):
                raise ValidationError("Path must be a string")
            modify_command["path"] = path

        if content_type is not None:
            if not isinstance(content_type, str):
                raise ValidationError("Content type must be a string")
            modify_command["content_type"] = content_type

        payload = [modify_command]

        try:
            self.logger.debug("Modifying file: %s", file_id)

            # Route through the shared request helper (like every other
            # command) instead of posting directly to the bare base_url,
            # which is missing the "api/" path segment the server expects.
            response = self._make_api_request("POST", "api/", self.auth_token, payload)

            # Check if modification was successful
            if len(response) >= 2 and isinstance(response[1], dict):
                result_entry = response[1]
                if "error" in result_entry:
                    raise FileAPIError(f"API error: {result_entry['error']}")
                modify_result = result_entry.get("result")
                if isinstance(modify_result, dict) and modify_result.get("error"):
                    raise FileAPIError(f"API error: {modify_result['error']}")
                if modify_result and "update file" in str(modify_result):
                    self.logger.info("Successfully modified file: %s", file_id)
                    return {
                        "result": modify_result,
                        "file_id": file_id,
                        "response": response,
                    }

            raise FileAPIError(
                f"Unexpected response format: {self._format_response_for_log(response)}"
            )

        except Exception as e:
            if isinstance(e, FileAPIError):
                raise
            raise FileAPIError(f"Failed to modify file: {e}") from e

    @api_tag(MethodType.API_COMMAND, api_command="deletefile")
    def delete_file(self, file_id: str) -> bool:
        """Delete file in Silo storage by file_id.

        Permanently deletes a file from Silo storage. This action cannot be undone.

        Args:
            file_id: ID of the file to delete

        Returns:
            True if deletion was successful, False otherwise

        Raises:
            FileAPIError: If file deletion fails
            ValidationError: If file_id is invalid

        Examples:
            >>> success = api.delete_file("abc123")
            >>> if success:
            ...     print("File deleted successfully")
        """
        if not file_id or not isinstance(file_id, str):
            raise ValidationError("File ID must be a non-empty string")

        payload = [
            {
                "command": "deletefile",
                "file_id": file_id,
            }
        ]

        try:
            self.logger.debug("Deleting file: %s", file_id)
            response = self._make_api_request("POST", "api/", self.auth_token, payload)

            result = self._extract_api_result(response)
            if isinstance(result, str) and "deleted file" in result:
                self.logger.info("Successfully deleted file: %s", file_id)
                return True
            if isinstance(result, dict) and (
                result.get("deleted") or result.get("success")
            ):
                self.logger.info("Successfully deleted file: %s", file_id)
                return True

            self.logger.warning("File deletion may have failed: %s", result)
            return False

        except Exception as e:
            if isinstance(e, FileAPIError):
                raise
            raise FileAPIError(f"Failed to delete file: {e}") from e

    @api_tag(MethodType.CONVENIENCE, wraps=["findfiles"])
    def get_file_info(
        self, file_id: str, bucket_id: str | None = None
    ) -> dict[str, Any]:
        """Get detailed information about a file.

        Retrieves information about a single file by listing the bucket and
        matching on ``file_id`` client-side.

        Warning:
            ``file_id`` is sent to ``findfiles`` but the platform drops it --
            the handler allowlists its arguments and ``file_id`` is not among
            them, the same reason ``find_files``' size bounds are applied on
            arrival. So this is a **full listing of the bucket** on every
            call; the server does not page, so a file in the bucket is always
            found. There is no scoped lookup on ``findfiles`` to use instead.

        Args:
            file_id: ID of the file to get information for
            bucket_id: Bucket to search in. If omitted, the configured
                ``BUCKET_ID`` is used.

        Returns:
            Dictionary containing detailed file information

        Raises:
            FileAPIError: If file information retrieval fails, or no bucket
                is given and ``BUCKET_ID`` is not configured (the server always
                rejects a ``findfiles`` without one, so this is raised before
                any request is sent)
            ValidationError: If file_id is invalid

        Examples:
            >>> file_info = api.get_file_info("abc123")
            >>> print(f"File: {file_info['name']}")
            >>> print(f"Size: {file_info['file_size']} bytes")
            >>> print(f"Created: {file_info['create_ts']}")
        """
        if not file_id or not isinstance(file_id, str):
            raise ValidationError("File ID must be a non-empty string")

        # Use the provided bucket_id or fall back to configured bucket
        search_bucket_id = bucket_id or self._config.get("BUCKET_ID")
        if not search_bucket_id:
            # FileAPIError, not ValidationError: before 0.16.1 this case reached
            # the server and came back as FileAPIError, and callers catch that.
            raise FileAPIError(
                "bucket_id is required: pass it or set BUCKET_ID "
                "(A8_BUCKET_ID); the server rejects findfiles without one"
            )

        try:
            self.logger.debug("Getting file info for: %s", file_id)

            # file_id is sent but dropped server-side: findfiles allowlists
            # its arguments and file_id is not on the list, so the full bucket
            # listing comes back and the loop below does the matching. Left in
            # the payload because it is harmless and becomes correct for free
            # if the platform ever accepts it -- but do not read this as a
            # scoped lookup; see the Warning in the docstring.
            find_command: dict[str, Any] = {
                "command": "findfiles",
                "file_id": file_id,
            }

            find_command["bucket_id"] = search_bucket_id

            payload = [find_command]

            response = self._make_api_request("POST", "api/", self.auth_token, payload)

            # Extract results and find the matching file_id
            if len(response) >= 2 and isinstance(response[1], dict):
                result_entry = response[1]
                if "error" in result_entry:
                    raise FileAPIError(f"API error: {result_entry['error']}")
                files_list = result_entry.get("result", [])
                if isinstance(files_list, dict) and files_list.get("error"):
                    raise FileAPIError(f"API error: {files_list['error']}")
                if isinstance(files_list, list):
                    # Find the file with matching file_id. The server-side
                    # filter should already narrow this to a single entry,
                    # but we still match explicitly in case the wire
                    # implementation returns extra entries.
                    for file_info in files_list:
                        if (
                            isinstance(file_info, dict)
                            and file_info.get("file_id") == file_id
                        ):
                            self.logger.debug("Found file information for: %s", file_id)
                            return file_info

                    # File not found in this bucket
                    raise FileAPIError(
                        f"File with ID {file_id} not found in bucket {search_bucket_id}"
                    )

            raise FileAPIError(
                f"Unexpected response format: {self._format_response_for_log(response)}"
            )

        except Exception as e:
            if isinstance(e, FileAPIError):
                raise
            raise FileAPIError(f"Failed to get file information: {e}") from e

    # Async Download Methods (require httpx)

    @api_tag(MethodType.ASYNC_VARIANT, api_command="getfile", sync_of="download_file")
    async def download_file_with_retry_async(
        self,
        file_id: str,
        output_path: str | Path,
        max_retries: int = 3,
        timeout: int = 60,
        create_dirs: bool = True,
        _client: httpx.AsyncClient | None = None,
    ) -> str:
        """Asynchronously download file by file_id with retry mechanism.
        Downloads a file from Silo storage with configurable retry logic and
        timeout handling. This async version allows for non-blocking downloads
        and can be used for concurrent file downloads.

        Args:
            file_id: ID of the file to download
            output_path: Path where to save the downloaded file
            max_retries: Positive maximum number of retry attempts (default: 3)
            timeout: Positive request timeout in seconds (default: 60)
            create_dirs: Whether to create parent directories if they don't exist
            _client: Internal. An open client to borrow instead of creating one,
                so a bulk caller can share a single connection pool across
                files. Not part of the public API.

        Returns:
            Path of the downloaded file (as string)

        Raises:
            FileAPIError: If file download fails, the server blocks the file
                as malware (HTTP 200 + JSON body), or the body is shorter than
                its Content-Length. Neither of those, nor a 500 reporting a
                malware scan failure, is retried.
            ValidationError: If parameters are invalid

        Examples:
            >>> import asyncio
            >>> async def download_files():
            ...     files = FileAPI(config)
            ...     downloaded_path = await files.download_file_with_retry_async(
            ...         file_id="abc123",
            ...         output_path="/home/user/downloads/report.pdf",
            ...         max_retries=5
            ...     )
            ...     return downloaded_path
            >>> path = asyncio.run(download_files())
        """
        validate_positive_int(max_retries, "max_retries")
        validate_positive_int(timeout, "timeout")

        if not file_id or not isinstance(file_id, str):
            raise ValidationError("File ID must be a non-empty string")

        if not output_path:
            raise ValidationError("Output path must be provided")

        # Convert to Path object
        output_path = Path(output_path)

        try:
            self.logger.debug(
                "Starting async download with retry for file ID: %s", file_id
            )

            await self._prepare_output_dir_async(output_path, create_dirs)

            download_url = f"{self.base_url.rstrip('/')}/getfile/"

            async with self._client_scope(_client) as client:
                for attempt in range(max_retries):
                    self.logger.debug(
                        f"Download attempt {attempt + 1} for file {file_id}"
                    )
                    try:
                        response = await client.post(
                            download_url,
                            data={"id": file_id, "auth": self.auth_token},
                            timeout=httpx.Timeout(timeout),
                        )
                        response.raise_for_status()
                        content = response.content

                        # Malware block: HTTP 200 + JSON, not the file. Raised
                        # outside the retry handler (not an httpx error) and
                        # before anything is written.
                        if _is_json_response(response):
                            blocked = _malware_error(content)
                            if blocked is not None:
                                raise blocked

                        expected = _expected_length(response)
                        if expected is not None and len(content) < expected:
                            raise _short_body_error(expected, len(content))

                        # Opening and writing both block; Path.write_bytes does
                        # all of it inside the worker thread so the event loop
                        # stays free for the other downloads in a bulk run.
                        try:
                            await asyncio.to_thread(output_path.write_bytes, content)
                        except OSError as write_error:
                            # write_bytes opens "wb", so it has already
                            # truncated whatever was at output_path before it
                            # failed. Retrying will not help a full disk or a
                            # revoked permission, and the sibling methods both
                            # clean up here -- leaving the remnant is what lets
                            # a caller mistake it for a complete download.
                            await asyncio.to_thread(
                                self._cleanup_partial_file, output_path
                            )
                            raise FileAPIError(
                                f"Failed to write downloaded file to "
                                f"{output_path}: {write_error}"
                            ) from write_error

                        self.logger.info(
                            "Successfully downloaded file to: %s", output_path
                        )
                        return str(output_path)

                    except httpx.HTTPError as e:
                        self.logger.error(
                            f"Error downloading file (attempt {attempt + 1}/{max_retries}): {e}"
                        )
                        if not _is_retryable(e):
                            raise (
                                _short_body_defect(e)
                                or FileAPIError(
                                    f"Failed to download file: {e}{_status_suffix(e)}"
                                )
                            ) from e
                        if attempt == max_retries - 1:
                            raise FileAPIError(
                                f"Failed to download file after {max_retries} "
                                f"attempts: {e}{_status_suffix(e)}"
                            ) from e
                        await asyncio.sleep(_retry_delay(e, attempt))

            # If we get here, all retries were exhausted without success
            raise FileAPIError(
                f"Failed to download file after {max_retries} attempts"
            )  # pragma: no cover

        except Exception as e:  # pragma: no cover
            if isinstance(e, FileAPIError):
                raise
            raise FileAPIError(f"Failed to download file with retry: {e}") from e

    @api_tag(MethodType.ASYNC_VARIANT, api_command="getfile", sync_of="download_file")
    async def download_file_chunked_async(
        self,
        file_id: str,
        output_path: str | Path,
        chunk_size: int = 8192,
        timeout: int = 60,
        create_dirs: bool = True,
        _client: httpx.AsyncClient | None = None,
    ) -> str:
        """Asynchronously download file by file_id using chunked download.
        Downloads a file from Silo storage using streaming/chunked approach,
        which is more memory-efficient for large files. This async version
        allows for non-blocking downloads of large files.

        Args:
            file_id: ID of the file to download
            output_path: Path where to save the downloaded file
            chunk_size: Positive size of chunks to read at a time (default: 8192)
            timeout: Positive request timeout in seconds (default: 60)
            create_dirs: Whether to create parent directories if they don't exist
            _client: Internal. An open client to borrow instead of creating one,
                so a bulk caller can share a single connection pool across
                files. Not part of the public API.

        Returns:
            Path of the downloaded file (as string)

        Raises:
            FileAPIError: If file download fails, the server blocks the file
                as malware (HTTP 200 + JSON body; no output file is created),
                or the body is shorter than its Content-Length (the partial
                file is removed).
            ValidationError: If parameters are invalid

        Examples:
            >>> import asyncio
            >>> async def download_large_file():
            ...     files = FileAPI(config)
            ...     downloaded_path = await files.download_file_chunked_async(
            ...         file_id="large_file_123",
            ...         output_path="/home/user/downloads/large_archive.zip",
            ...         chunk_size=16384
            ...     )
            ...     return downloaded_path
            >>> path = asyncio.run(download_large_file())
        """
        validate_positive_int(chunk_size, "chunk_size")
        validate_positive_int(timeout, "timeout")

        if not file_id or not isinstance(file_id, str):
            raise ValidationError("File ID must be a non-empty string")

        if not output_path:
            raise ValidationError("Output path must be provided")

        # Convert to Path object
        output_path = Path(output_path)

        try:
            self.logger.debug(
                "Starting async chunked download for file ID: %s", file_id
            )

            await self._prepare_output_dir_async(output_path, create_dirs)

            download_url = f"{self.base_url.rstrip('/')}/getfile/"

            async with self._client_scope(_client) as client:
                try:
                    async with client.stream(
                        "POST",
                        download_url,
                        data={"id": file_id, "auth": self.auth_token},
                        timeout=httpx.Timeout(timeout),
                    ) as response:
                        try:
                            response.raise_for_status()
                        except httpx.HTTPStatusError:
                            # Streamed body is unread; load it so the error
                            # can carry the server's reason.
                            try:
                                await response.aread()
                            except httpx.HTTPError:
                                pass
                            raise

                        # Malware block: HTTP 200 + JSON instead of the file.
                        # Checked before the output file is opened, so nothing
                        # is created. A genuine JSON body is already buffered
                        # by aread() and still streams out below.
                        if _is_json_response(response):
                            await response.aread()
                            blocked = _malware_error(response.content)
                            if blocked is not None:
                                raise blocked

                        expected = _expected_length(response)
                        received = 0

                        try:
                            # open() and close() block exactly as the writes
                            # do, so they go to a thread too -- they were the
                            # last inline filesystem calls left in this method
                            # after the chunk writes were offloaded, and an
                            # offload that skips them still stalls the loop
                            # once per download. Hence the explicit
                            # open/try/finally rather than a `with`: the close
                            # has to be awaited.
                            f = await asyncio.to_thread(open, output_path, "wb")
                            try:
                                # Accumulate then offload. Writing each chunk
                                # inline blocked the event loop on disk for
                                # every 8 KiB of every concurrent download,
                                # which is exactly the stall streaming
                                # concurrently is supposed to avoid.
                                buffer = bytearray()
                                async for chunk in response.aiter_bytes(chunk_size):
                                    received += len(chunk)
                                    buffer += chunk
                                    if len(buffer) >= _WRITE_BUFFER_BYTES:
                                        await asyncio.to_thread(f.write, bytes(buffer))
                                        buffer.clear()
                                if buffer:
                                    await asyncio.to_thread(f.write, bytes(buffer))
                            finally:
                                await asyncio.to_thread(f.close)
                            if expected is not None and received < expected:
                                raise _short_body_error(expected, received)
                        except Exception:
                            # The finally above has closed the file by now
                            # (and if open() itself failed there is nothing
                            # to close), so this only ever unlinks a closed
                            # path. unlink blocks like any other filesystem
                            # call, so it goes to a thread for the same
                            # reason the writes do -- and to match the retry
                            # variant.
                            await asyncio.to_thread(
                                self._cleanup_partial_file, output_path
                            )
                            raise

                        self.logger.info(
                            "Successfully downloaded file to: %s", output_path
                        )
                        return str(output_path)

                except httpx.HTTPError as e:
                    raise (
                        _short_body_defect(e)
                        or FileAPIError(
                            f"Failed to download file: {e}{_status_suffix(e)}"
                        )
                    ) from e

        except Exception as e:
            if isinstance(e, FileAPIError):
                raise
            raise FileAPIError(f"Failed to download file chunked: {e}") from e

    @api_tag(
        MethodType.ASYNC_CONVENIENCE,
        wraps=["download_file_with_retry_async", "download_file_chunked_async"],
    )
    async def bulk_download_async(
        self,
        file_downloads: list[dict[str, Any]],
        max_concurrent: int = 5,
        use_chunked: bool = False,
    ) -> list[str | None]:
        """Download multiple files concurrently.

        Downloads multiple files in parallel with configurable concurrency
        limits to efficiently handle bulk file downloads.

        Args:
            file_downloads: List of download dictionaries, each containing:
                - file_id: ID of the file to download
                - output_path: Path where to save the file
                - max_retries: Optional max retries (default: 3)
                - timeout: Optional timeout (default: 60)
                - chunk_size: Optional chunk size for chunked downloads
            max_concurrent: Positive maximum number of concurrent downloads
                (default: 5), up to ``_MAX_BULK_CONCURRENCY``. The batch's
                shared connection pool is sized to match.
            use_chunked: Which per-file download to run (default: ``False``).
                The two differ in more than chunk size, so the choice is a
                trade-off rather than a tuning knob:

                - ``False`` — ``download_file_with_retry_async``: retries
                    transient failures, but buffers each response body in
                    memory before writing. Peak memory is roughly
                    ``max_concurrent`` × largest file.
                - ``True`` — ``download_file_chunked_async``: streams to disk
                    so memory stays bounded regardless of file size, but has
                    **no retry loop** — a dropped connection fails that file
                    and returns ``None`` for it.

                Prefer ``True`` for large files, and re-issue the failures
                yourself; prefer the default when files are small enough to
                buffer and you would rather the SDK absorb a flaky network.

        Returns:
            List of downloaded file paths (same order as input), None for failed downloads

        Raises:
            ValidationError: If parameters are invalid

        Examples:
            >>> import asyncio
            >>> async def bulk_download():
            ...     files = FileAPI(config)
            ...     downloads = [
            ...         {"file_id": "file1", "output_path": "./downloads/file1.pdf"},
            ...         {"file_id": "file2", "output_path": "./downloads/file2.zip"},
            ...     ]
            ...     results = await files.bulk_download_async(
            ...         file_downloads=downloads,
            ...         max_concurrent=3
            ...     )
            ...     return results
            >>> results = asyncio.run(bulk_download())
        """
        validate_positive_int(max_concurrent, "max_concurrent")
        if max_concurrent > _MAX_BULK_CONCURRENCY:
            raise ValidationError(
                f"max_concurrent must be at most {_MAX_BULK_CONCURRENCY}"
            )

        # Create semaphore to limit concurrent downloads
        semaphore = asyncio.Semaphore(max_concurrent)

        async def download_single_file(
            download_config: dict[str, Any],
            client: httpx.AsyncClient,
        ) -> str | None:
            """Download a single file with semaphore control."""
            async with semaphore:
                try:
                    file_id = download_config["file_id"]
                    output_path = download_config["output_path"]
                    max_retries = download_config.get("max_retries", 3)
                    timeout = download_config.get("timeout", 60)

                    if use_chunked:
                        chunk_size = download_config.get("chunk_size", 8192)
                        return await self.download_file_chunked_async(
                            file_id=file_id,
                            output_path=output_path,
                            chunk_size=chunk_size,
                            timeout=timeout,
                            _client=client,
                        )
                    else:
                        return await self.download_file_with_retry_async(
                            file_id=file_id,
                            output_path=output_path,
                            max_retries=max_retries,
                            timeout=timeout,
                            _client=client,
                        )
                except Exception as e:
                    self.logger.error(
                        f"Failed to download {download_config.get('file_id')}: {e}"
                    )
                    return None

        # Process all downloads concurrently. One client for the whole batch:
        # the per-download methods accept it rather than each opening their
        # own, so the batch shares a single connection pool instead of paying
        # a TLS handshake per file. The pool is sized to the semaphore so the
        # two agree -- httpx's default keepalive of 20 would otherwise close
        # and reopen connections underneath a wider batch.
        self.logger.info(f"Starting bulk download of {len(file_downloads)} files")
        async with httpx.AsyncClient(
            verify=self._ssl_context,
            limits=httpx.Limits(
                max_connections=max_concurrent,
                max_keepalive_connections=max_concurrent,
            ),
        ) as client:
            results = await asyncio.gather(
                *[
                    download_single_file(download, client)
                    for download in file_downloads
                ],
                return_exceptions=True,
            )

        # Convert exceptions to None and log errors
        processed_results: list[str | None] = []
        for i, result in enumerate(results):
            if isinstance(result, Exception):
                self.logger.error(f"Download {i + 1} failed with exception: {result}")
                processed_results.append(None)
            elif isinstance(result, str):
                processed_results.append(result)
            else:
                processed_results.append(None)

        successful_downloads = sum(1 for r in processed_results if r is not None)
        self.logger.info(
            f"Completed bulk download: {successful_downloads}/{len(file_downloads)} "
            "files successful"
        )

        return processed_results

__init__

__init__(config: dict[str, Any]) -> None

Initialize the file storage API client.

Parameters:

Name Type Description Default
config dict[str, Any]

Configuration dictionary containing API settings

required

Raises:

Type Description
ConfigurationError

If required configuration is missing

Source code in silo_sdk/storage/file_api.py
def __init__(self, config: dict[str, Any]) -> None:
    """Initialize the file storage API client.

    Args:
        config: Configuration dictionary containing API settings

    Raises:
        ConfigurationError: If required configuration is missing
    """
    super().__init__(config)

    # Validate required configuration
    validate_config_for_api(config, ["FILE_TOKEN"])

    self.auth_token = config["FILE_TOKEN"]
    self._config = config  # Store config for later use
    # Built once, not per download. create_ssl_context() parses the certifi
    # CA bundle off disk every call, so building it inside a request path
    # meant bulk_download_async re-parsed it once per file. Matches what
    # HarvesterAPI already does.
    self._ssl_context = self.create_ssl_context()
    self.logger.info("Initialized FileAPI client")

upload_file

upload_file(bucket_id: str, file_path: str | Path, name: str, path: str = '/', content_type: str | None = None) -> dict[str, Any]

Upload file from local system to Silo storage.

Uploads a file from the local filesystem to the specified bucket in Silo storage with the given name and path.

Parameters:

Name Type Description Default
bucket_id str

ID of the destination bucket (required)

required
file_path str | Path

Path to the local file to upload (required)

required
name str

Name to give the file in Silo storage (required)

required
path str

Path in Silo storage to store the file (optional, defaults to "/")

'/'
content_type str | None

MIME content type of the file (optional, auto-detected if not provided)

None

Returns:

Type Description
dict[str, Any]

Dictionary with a single key, file_id -- the identifier of

dict[str, Any]

the newly created file record. The response body is returned

dict[str, Any]

verbatim.

Warning

/putfile/ returns only file_id. An earlier version of this docstring also promised name, path, size, content_type and upload_ts; none of them are sent, and reading one raises KeyError. To get the rest of the record, call :meth:get_file_info with the returned file_id.

Raises:

Type Description
FileAPIError

If file upload fails. For a non-2xx response the server's reason (e.g. "file already exists", "bad auth") is included in the message. Also raised, before anything is sent, for a name containing ^, %, backslash or /, or a path containing ^, % or backslash (the server always rejects these).

ValidationError

If other parameters are invalid

Examples:

>>> result = api.upload_file(
...     bucket_id="documents",
...     file_path="/home/user/report.pdf",
...     name="quarterly_report.pdf",
...     path="/reports/2024/"
... )
>>> print(f"Uploaded file ID: {result['file_id']}")
Source code in silo_sdk/storage/file_api.py
@api_tag(MethodType.API_COMMAND, api_command="putfile")
def upload_file(
    self,
    bucket_id: str,
    file_path: str | Path,
    name: str,
    path: str = "/",
    content_type: str | None = None,
) -> dict[str, Any]:
    """Upload file from local system to Silo storage.

    Uploads a file from the local filesystem to the specified bucket in
    Silo storage with the given name and path.

    Args:
        bucket_id: ID of the destination bucket (required)
        file_path: Path to the local file to upload (required)
        name: Name to give the file in Silo storage (required)
        path: Path in Silo storage to store the file (optional, defaults to "/")
        content_type: MIME content type of the file (optional, auto-detected if not provided)

    Returns:
        Dictionary with a single key, ``file_id`` -- the identifier of
        the newly created file record. The response body is returned
        verbatim.

    Warning:
        ``/putfile/`` returns **only** ``file_id``. An earlier version of
        this docstring also promised ``name``, ``path``, ``size``,
        ``content_type`` and ``upload_ts``; none of them are sent, and
        reading one raises ``KeyError``. To get the rest of the record,
        call :meth:`get_file_info` with the returned ``file_id``.

    Raises:
        FileAPIError: If file upload fails. For a non-2xx response the
            server's reason (e.g. "file already exists", "bad auth") is
            included in the message. Also raised, before anything is
            sent, for a ``name`` containing ``^``, ``%``, backslash or
            ``/``, or a ``path`` containing ``^``, ``%`` or backslash
            (the server always rejects these).
        ValidationError: If other parameters are invalid

    Examples:
        >>> result = api.upload_file(
        ...     bucket_id="documents",
        ...     file_path="/home/user/report.pdf",
        ...     name="quarterly_report.pdf",
        ...     path="/reports/2024/"
        ... )
        >>> print(f"Uploaded file ID: {result['file_id']}")
    """
    # Validate parameters
    if not bucket_id or not isinstance(bucket_id, str):
        raise ValidationError("Bucket ID must be a non-empty string")

    if not name or not isinstance(name, str):
        raise ValidationError("File name must be a non-empty string")

    if not isinstance(path, str):
        raise ValidationError("Path must be a string")

    # The server always rejects these characters; say so before uploading.
    # FileAPIError, not ValidationError: before 0.16.1 these reached the
    # server and came back as FileAPIError, and callers catch that.
    bad_name = [c for c in _BAD_NAME_CHARS if c in name]
    if bad_name:
        raise FileAPIError(
            f"File name must not contain any of {' '.join(_BAD_NAME_CHARS)} "
            f"(found {' '.join(bad_name)}); the server rejects them"
        )
    bad_path = [c for c in _BAD_PATH_CHARS if c in path]
    if bad_path:
        raise FileAPIError(
            f"Path must not contain any of {' '.join(_BAD_PATH_CHARS)} "
            f"(found {' '.join(bad_path)}); the server rejects them"
        )

    # Convert to Path object and validate file exists
    file_path = Path(file_path)
    if not file_path.exists():
        raise ValidationError(f"File does not exist: {file_path}")

    if not file_path.is_file():
        raise ValidationError(f"Path is not a file: {file_path}")

    # Auto-detect content type if not provided
    if content_type is None:
        import mimetypes

        content_type, _ = mimetypes.guess_type(str(file_path))
        if content_type is None:
            content_type = "application/octet-stream"

    # Prepare upload data for /putfile/ endpoint
    url = f"{self.base_url.rstrip('/')}/putfile/"

    try:
        self.logger.debug(
            "Uploading file: %s to bucket: %s", file_path.name, bucket_id
        )
        self.logger.debug("Upload URL: %s", url)

        with open(file_path, "rb") as f:
            # Prepare form data for /putfile/ endpoint
            data = {
                "auth": self.auth_token,
                "bucket_id": bucket_id,
                "name": name,
                "path": path,
            }

            # Add optional parameters
            if content_type:
                data["content_type"] = content_type

            files = {"file": (file_path.name, f, content_type)}

            # Debug logging
            self.logger.debug("Data keys: %s", list(data.keys()))
            self.logger.debug("Files keys: %s", list(files.keys()))

            # Route through the shared session so retry/proxy/User-Agent
            # configuration from BaseAPIClient is honored. Override
            # Content-Type (set to None to drop the session's default
            # "application/json") so requests can compute the correct
            # multipart/form-data boundary itself.
            response = self.session.post(
                url,
                data=data,
                files=files,
                timeout=self.timeout,
                headers={"Content-Type": None},
            )

            # Log response details for debugging
            self.logger.debug("Response status: %s", response.status_code)
            if not response.ok:
                self.logger.error("Response content: %s", response.text)

            _raise_for_status(response, "upload file")

            result: dict[str, Any] = response.json()
            self.logger.info("Successfully uploaded file: %s", name)
            return result

    except Exception as e:
        if isinstance(e, FileAPIError):
            raise
        raise FileAPIError(f"Failed to upload file: {e}") from e

download_file

download_file(file_id: str, output_path: str | Path, create_dirs: bool = True) -> str

Download file by file_id from Silo storage.

Downloads a file from Silo storage to the local filesystem using the file's unique identifier.

Parameters:

Name Type Description Default
file_id str

ID of the file to download

required
output_path str | Path

Path where to save the downloaded file

required
create_dirs bool

Whether to create parent directories if they don't exist

True
Note

Wire endpoint: POST https://extapi.authentic8.com/getfile/ with form-data fields id (file ID) and auth (file token). This is not a JSON command-array request — it uses a separate endpoint and multipart form-data, not the standard /api/ command format. The response body is the raw file content (binary stream).

Warning

The server reports a malware-blocked file as HTTP 200 with a JSON body (error, malware, ...) instead of the file. That is raised as FileAPIError and nothing is written. A body shorter than its Content-Length is also an error (on some files the server's Content-Length exceeds the body by exactly 28 bytes -- a known server defect).

Returns:

Type Description
str

Path of the downloaded file (as string)

Raises:

Type Description
FileAPIError

If file download fails, the server blocks the file as malware, or the body is truncated. For a non-2xx response the server's reason (e.g. "file is folder", "file not found", "bad auth") is included in the message.

ValidationError

If parameters are invalid

Examples:

>>> downloaded_path = api.download_file(
...     file_id="abc123",
...     output_path="/home/user/downloads/report.pdf"
... )
>>> print(f"File downloaded to: {downloaded_path}")
Source code in silo_sdk/storage/file_api.py
@api_tag(MethodType.API_COMMAND, api_command="getfile")
def download_file(
    self,
    file_id: str,
    output_path: str | Path,
    create_dirs: bool = True,
) -> str:
    """Download file by file_id from Silo storage.

    Downloads a file from Silo storage to the local filesystem using the
    file's unique identifier.

    Args:
        file_id: ID of the file to download
        output_path: Path where to save the downloaded file
        create_dirs: Whether to create parent directories if they don't exist

    Note:
        Wire endpoint: ``POST https://extapi.authentic8.com/getfile/`` with
        form-data fields ``id`` (file ID) and ``auth`` (file token). This is
        **not** a JSON command-array request — it uses a separate endpoint
        and multipart form-data, not the standard ``/api/`` command format.
        The response body is the raw file content (binary stream).

    Warning:
        The server reports a malware-blocked file as **HTTP 200** with a
        JSON body (``error``, ``malware``, ...) instead of the file. That
        is raised as ``FileAPIError`` and nothing is written. A body
        shorter than its ``Content-Length`` is also an error (on some
        files the server's Content-Length exceeds the body by exactly 28
        bytes -- a known server defect).

    Returns:
        Path of the downloaded file (as string)

    Raises:
        FileAPIError: If file download fails, the server blocks the file
            as malware, or the body is truncated. For a non-2xx response
            the server's reason (e.g. "file is folder", "file not found",
            "bad auth") is included in the message.
        ValidationError: If parameters are invalid

    Examples:
        >>> downloaded_path = api.download_file(
        ...     file_id="abc123",
        ...     output_path="/home/user/downloads/report.pdf"
        ... )
        >>> print(f"File downloaded to: {downloaded_path}")
    """
    if not file_id or not isinstance(file_id, str):
        raise ValidationError("File ID must be a non-empty string")

    if not output_path:
        raise ValidationError("Output path must be provided")

    # Convert to Path object and resolve to prevent path traversal
    output_path_raw = str(output_path)
    output_path = Path(output_path).resolve()

    # Warn if the original path contained traversal components
    if ".." in output_path_raw:
        self.logger.warning(
            "Output path contained '..' components, resolved to: %s",
            output_path,
        )

    # Create parent directories if requested
    if create_dirs and output_path.parent != output_path:
        output_path.parent.mkdir(parents=True, exist_ok=True)

    url = f"{self.base_url.rstrip('/')}/getfile/"

    try:
        self.logger.debug("Downloading file ID: %s", file_id)

        data = {
            "id": file_id,
            "auth": self.auth_token,
        }

        # Route through the shared session so retry/proxy/User-Agent
        # configuration from BaseAPIClient is honored. Override
        # Content-Type (set to None to drop the session's default
        # "application/json") so requests encodes the form body correctly.
        response = self.session.post(
            url,
            data=data,
            timeout=self.timeout,
            stream=True,
            headers={"Content-Type": None},
        )
        _raise_for_status(response, "download file")

        # A malware-blocked file comes back as HTTP 200 with a JSON
        # description instead of the file; never write that as content.
        if _is_json_response(response):
            blocked = _malware_error(response.content)
            if blocked is not None:
                raise blocked

        expected = _expected_length(response)
        received = 0

        # Write file content
        try:
            with open(output_path, "wb") as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        f.write(chunk)
                        received += len(chunk)
            if expected is not None and received < expected:
                raise _short_body_error(expected, received)
        except Exception:
            self._cleanup_partial_file(output_path)
            raise

        self.logger.info("Successfully downloaded file to: %s", output_path)
        return str(output_path)

    except Exception as e:
        if isinstance(e, FileAPIError):
            raise
        defect = _short_body_defect(e)
        if defect is not None:
            raise defect from e
        raise FileAPIError(f"Failed to download file: {e}") from e

find_files

find_files(bucket_id: str, name: str | None = None, path: str | None = None, file_type: str | None = None, created_before: str | None = None, created_after: str | None = None, size_min: int | None = None, size_max: int | None = None, limit: int | None = None, metadata_filters: dict[str, str] | None = None) -> list[dict[str, Any]]

Search Silo storage for files by various criteria.

Searches for files in the specified bucket by name, path, kind, creation date, and file size.

Parameters:

Name Type Description Default
bucket_id str

ID of the bucket to search in.

required
name str | None

File name to match. Exact, case-insensitive match -- there are no wildcards ("*" and "*.txt" match nothing).

None
path str | None

Folder to list. Exact match, direct children only -- not recursive, and no wildcards.

None
file_type str | None

Filter by kind: "file" or "directory" only. It is not a MIME type or extension filter ("application/pdf" matches nothing). Sent as "type" in the wire format (field name differs from this parameter name).

None
created_before str | None

Search for files created before this date (ISO format). Sent as ":created_before" in the wire format (note the colon prefix on the wire field name).

None
created_after str | None

Search for files created after this date (ISO format). Sent as ":created_after" in the wire format (note the colon prefix on the wire field name).

None
size_min int | None

Minimum file size in bytes. Applied here, not by the server -- see limit below; the server's findfiles allowlist has no size fields, so it silently ignores these. Records are matched on the wire field "file_size". Directories carry "file_size": null and are therefore excluded whenever either size bound is given.

None
size_max int | None

Maximum file size in bytes. Same handling as size_min.

None
limit int | None

Maximum number of results to return. Applied here, not by the server. The value is still sent on the wire, but live testing shows the server returns the full listing regardless, so the list is truncated on arrival to keep the documented contract true. Expect no bandwidth saving from it.

None
metadata_filters dict[str, str] | None

Has no effect. The server ignores these and the SDK does not apply them, so the full listing is returned; a warning is emitted when supplied. Kept for signature compatibility.

None
Note

Wire format parameter name differences:

  • Python file_type → wire "type"
  • Python created_before → wire ":created_before" (colon prefix)
  • Python created_after → wire ":created_after" (colon prefix)

Wire format structure::

{
    "command": "findfiles",
    "bucket_id": "my_bucket",
    "type": "file",                     # ← file_type → "type"
    ":created_before": "2026-01-01",    # ← colon prefix
    ":created_after": "2025-01-01"      # ← colon prefix
}

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries, one per matching file. The result is passed

list[dict[str, Any]]

through unfiltered, so a field the platform adds appears here

list[dict[str, Any]]

without an SDK change. Fields returned:

list[dict[str, Any]]
  • bucket_id: Bucket the file lives in
list[dict[str, Any]]
  • file_id: Unique file identifier
list[dict[str, Any]]
  • name: File name
list[dict[str, Any]]
  • path: File path in storage
list[dict[str, Any]]
  • type: File type
list[dict[str, Any]]
  • content_type: MIME type
list[dict[str, Any]]
  • file_size: File size in bytes
list[dict[str, Any]]
  • create_user_id: ID of the account that created the file
list[dict[str, Any]]
  • create_username: Name of the account that created the file
list[dict[str, Any]]
  • create_ts: Creation timestamp (ISO-8601)
list[dict[str, Any]]
  • expire_ts: Expiry timestamp (ISO-8601)
list[dict[str, Any]]
  • uploading_until: Upload deadline (ISO-8601)
list[dict[str, Any]]
  • session_id: Session that created the file. Not always present -- records created outside a browsing session omit it, so use .get("session_id").
list[dict[str, Any]]

session_id lets you correlate a stored file with the session

list[dict[str, Any]]

activity that produced it.

list[dict[str, Any]]

The creating account is reported as two fields,

list[dict[str, Any]]

create_user_id and create_username. There is no

list[dict[str, Any]]

create_user; an earlier version of this list named one.

list[dict[str, Any]]

Directories are included in the listing, carrying a

list[dict[str, Any]]

content_type of Folder. They are not downloadable —

list[dict[str, Any]]

meth:download_file and :meth:bulk_download_async get an API

list[dict[str, Any]]

error for one — so filter them out before feeding these entries to

list[dict[str, Any]]

a download.

Raises:

Type Description
FileAPIError

If file search fails

ValidationError

If parameters are invalid

Examples:

>>> files = api.find_files(
...     bucket_id="documents",
...     name="report.pdf",
...     path="/reports/",
...     created_after="2024-01-01T00:00:00Z",
...     size_min=1024,
...     limit=100
... )
>>> for file in files:
...     print(f"{file['name']} - {file['file_size']} bytes")
Source code in silo_sdk/storage/file_api.py
@api_tag(MethodType.API_COMMAND, api_command="findfiles")
def find_files(
    self,
    bucket_id: str,
    name: str | None = None,
    path: str | None = None,
    file_type: str | None = None,
    created_before: str | None = None,
    created_after: str | None = None,
    size_min: int | None = None,
    size_max: int | None = None,
    limit: int | None = None,
    metadata_filters: dict[str, str] | None = None,
) -> list[dict[str, Any]]:
    """Search Silo storage for files by various criteria.

    Searches for files in the specified bucket by name, path, kind,
    creation date, and file size.

    Args:
        bucket_id: ID of the bucket to search in.
        name: File name to match. **Exact, case-insensitive match** --
            there are no wildcards (``"*"`` and ``"*.txt"`` match nothing).
        path: Folder to list. **Exact match, direct children only** -- not
            recursive, and no wildcards.
        file_type: Filter by kind: ``"file"`` or ``"directory"`` only. It
            is **not** a MIME type or extension filter
            (``"application/pdf"`` matches nothing). Sent as
            ``"type"`` in the wire format (field name differs from this
            parameter name).
        created_before: Search for files created before this date (ISO
            format). Sent as ``":created_before"`` in the wire format
            (note the colon prefix on the wire field name).
        created_after: Search for files created after this date (ISO
            format). Sent as ``":created_after"`` in the wire format
            (note the colon prefix on the wire field name).
        size_min: Minimum file size in bytes. **Applied here, not by the
            server** -- see ``limit`` below; the server's ``findfiles``
            allowlist has no size fields, so it silently ignores these.
            Records are matched on the wire field ``"file_size"``.
            Directories carry ``"file_size": null`` and are therefore
            excluded whenever either size bound is given.
        size_max: Maximum file size in bytes. Same handling as ``size_min``.
        limit: Maximum number of results to return. **Applied here, not by
            the server.** The value is still sent on the wire, but live
            testing shows the server returns the full listing regardless,
            so the list is truncated on arrival to keep the documented
            contract true. Expect no bandwidth saving from it.
        metadata_filters: **Has no effect.** The server ignores these
            and the SDK does not apply them, so the full listing is
            returned; a warning is emitted when supplied. Kept for
            signature compatibility.

    Note:
        Wire format parameter name differences:

        - Python ``file_type`` → wire ``"type"``
        - Python ``created_before`` → wire ``":created_before"`` (colon prefix)
        - Python ``created_after`` → wire ``":created_after"`` (colon prefix)

        Wire format structure::

            {
                "command": "findfiles",
                "bucket_id": "my_bucket",
                "type": "file",                     # ← file_type → "type"
                ":created_before": "2026-01-01",    # ← colon prefix
                ":created_after": "2025-01-01"      # ← colon prefix
            }

    Returns:
        List of dictionaries, one per matching file. The result is passed
        through unfiltered, so a field the platform adds appears here
        without an SDK change. Fields returned:

        - ``bucket_id``: Bucket the file lives in
        - ``file_id``: Unique file identifier
        - ``name``: File name
        - ``path``: File path in storage
        - ``type``: File type
        - ``content_type``: MIME type
        - ``file_size``: File size in bytes
        - ``create_user_id``: ID of the account that created the file
        - ``create_username``: Name of the account that created the file
        - ``create_ts``: Creation timestamp (ISO-8601)
        - ``expire_ts``: Expiry timestamp (ISO-8601)
        - ``uploading_until``: Upload deadline (ISO-8601)
        - ``session_id``: Session that created the file. **Not always
            present** -- records created outside a browsing session omit
            it, so use ``.get("session_id")``.

        ``session_id`` lets you correlate a stored file with the session
        activity that produced it.

        The creating account is reported as **two** fields,
        ``create_user_id`` and ``create_username``. There is no
        ``create_user``; an earlier version of this list named one.

        **Directories are included in the listing**, carrying a
        ``content_type`` of ``Folder``. They are not downloadable —
        :meth:`download_file` and :meth:`bulk_download_async` get an API
        error for one — so filter them out before feeding these entries to
        a download.

    Raises:
        FileAPIError: If file search fails
        ValidationError: If parameters are invalid

    Examples:
        >>> files = api.find_files(
        ...     bucket_id="documents",
        ...     name="report.pdf",
        ...     path="/reports/",
        ...     created_after="2024-01-01T00:00:00Z",
        ...     size_min=1024,
        ...     limit=100
        ... )
        >>> for file in files:
        ...     print(f"{file['name']} - {file['file_size']} bytes")
    """
    if not bucket_id or not isinstance(bucket_id, str):
        raise ValidationError("Bucket ID must be a non-empty string")

    # Build search payload
    search_params: dict[str, Any] = {
        "command": "findfiles",
        "bucket_id": bucket_id,
    }

    # Add optional search criteria
    if name is not None:
        search_params["name"] = name

    if path is not None:
        search_params["path"] = path

    if file_type is not None:
        search_params["type"] = file_type

    if created_before is not None:
        search_params[":created_before"] = created_before

    if created_after is not None:
        search_params[":created_after"] = created_after

    if size_min is not None:
        if not isinstance(size_min, int) or size_min < 0:
            raise ValidationError("size_min must be a non-negative integer")
        search_params["size_min"] = size_min

    if size_max is not None:
        if not isinstance(size_max, int) or size_max < 0:
            raise ValidationError("size_max must be a non-negative integer")
        search_params["size_max"] = size_max

    if limit is not None:
        if not isinstance(limit, int) or limit <= 0:
            raise ValidationError("limit must be a positive integer")
        search_params["limit"] = limit

    if metadata_filters is not None:
        if not isinstance(metadata_filters, dict):
            raise ValidationError("metadata_filters must be a dictionary")
        # Add metadata filters to search parameters
        for key, value in metadata_filters.items():
            search_params[f"metadata:{key}"] = value
        if metadata_filters:
            self.logger.warning(_METADATA_FILTERS_NOTE)
            warnings.warn(_METADATA_FILTERS_NOTE, UserWarning, stacklevel=2)

    payload = [search_params]

    try:
        self.logger.debug("Searching for files in bucket: %s", bucket_id)
        response = self._make_api_request("POST", "api/", self.auth_token, payload)

        # Extract results
        if len(response) >= 2 and isinstance(response[1], dict):
            result_entry = response[1]
            if "error" in result_entry:
                raise FileAPIError(f"API error: {result_entry['error']}")
            result = result_entry.get("result")
            # The error can also arrive nested inside the result. Returning
            # [] for it made a rejected search indistinguishable from an
            # empty bucket.
            if isinstance(result, dict) and result.get("error"):
                raise FileAPIError(f"API error: {result['error']}")
            if isinstance(result, list):
                if size_min is not None or size_max is not None:
                    # "size_min"/"size_max" are sent, but findfiles'
                    # server-side allowlist has no size fields, so they are
                    # dropped without error -- same shape as "limit" below.
                    # Filter here, before the limit slice: truncating first
                    # would return fewer than `limit` matches even when
                    # enough exist. Directories report "file_size": null
                    # and cannot satisfy a size bound, so they drop out.
                    unfiltered = len(result)
                    result = [
                        f
                        for f in result
                        if isinstance(f.get("file_size"), int)
                        and (size_min is None or f["file_size"] >= size_min)
                        and (size_max is None or f["file_size"] <= size_max)
                    ]
                    if len(result) != unfiltered:
                        self.logger.debug(
                            "Server returned %d results ignoring the size "
                            "bounds; %d match after client-side filtering",
                            unfiltered,
                            len(result),
                        )
                self.logger.info("Found %d files matching criteria", len(result))
                if limit is not None and len(result) > limit:
                    # The server accepts "limit" and ignores it -- a bucket
                    # of 109 answers limit=2 with all 109. Nothing here
                    # truncated either, so the documented cap was simply
                    # untrue and callers paging on it got the whole bucket.
                    # Enforcing it client-side costs one slice and makes
                    # the signature honest; it cannot save the transfer,
                    # which is why the docstring says so out loud.
                    self.logger.debug(
                        "Server returned %d results for limit=%d; "
                        "truncating client-side",
                        len(result),
                        limit,
                    )
                    return result[:limit]
                return result

        # Only a list result is a listing; an empty bucket is {"result": []}.
        # Anything else is raised rather than passed off as "no files".
        rendered = self._format_response_for_log(response)
        self.logger.warning(
            "Unexpected response format for find_files: %s", rendered
        )
        raise FileAPIError(f"Unexpected response format: {rendered}")

    except Exception as e:
        if isinstance(e, FileAPIError):
            raise
        raise FileAPIError(f"Failed to search for files: {e}") from e

list_files

list_files(bucket_id: str, limit: int | None = None) -> list[dict[str, Any]]

List files in a bucket.

Lists files in the specified bucket with optional limit. This is a convenience wrapper around find_files with no filters.

Parameters:

Name Type Description Default
bucket_id str

ID of the bucket to list files from

required
limit int | None

Maximum number of files to return. Enforced client-side — see :meth:find_files for why.

None

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries containing file information. Includes

list[dict[str, Any]]

directories (content_type of Folder), which are not

list[dict[str, Any]]

downloadable — filter before passing these to a download.

Raises:

Type Description
FileAPIError

If file listing fails

ValidationError

If parameters are invalid

Source code in silo_sdk/storage/file_api.py
@api_tag(MethodType.CONVENIENCE, wraps=["findfiles"])
def list_files(
    self,
    bucket_id: str,
    limit: int | None = None,
) -> list[dict[str, Any]]:
    """List files in a bucket.

    Lists files in the specified bucket with optional limit.
    This is a convenience wrapper around find_files with no filters.

    Args:
        bucket_id: ID of the bucket to list files from
        limit: Maximum number of files to return. Enforced client-side —
            see :meth:`find_files` for why.

    Returns:
        List of dictionaries containing file information. Includes
        directories (``content_type`` of ``Folder``), which are not
        downloadable — filter before passing these to a download.

    Raises:
        FileAPIError: If file listing fails
        ValidationError: If parameters are invalid
    """
    return self.find_files(bucket_id=bucket_id, limit=limit)

modify_file

modify_file(file_id: str, name: str | None = None, expire_ts: str | int | float | None = None, path: str | None = None, content_type: str | None = None) -> dict[str, Any]

Change properties of a file by file_id in Silo storage.

Modifies various properties of an existing file including its name, path, expiration time, and content type.

Parameters:

Name Type Description Default
file_id str

ID of the file to modify (required)

required
name str | None

New name for the file (optional)

None
expire_ts str | int | float | None

New file expiry (optional). An int/float is sent as a string. Accepted forms:

  • epoch seconds, e.g. 1767225600
  • "now+SECONDS" -- that long from now, e.g. "now+3600"
  • "+SECONDS" -- extend the current expiry by that long; the server errors on a non-expiring file ("cannot extend expire time for non-expiring file")
  • "reset" -- the bucket's default expiry; errors if the bucket has none ("bucket has no expire time to reset to")
  • an ISO-8601 timestamp string
None
path str | None

Path of new location to move file (optional)

None
content_type str | None

New content type of modified file (optional)

None

Returns:

Type Description
dict[str, Any]

Dictionary containing the API response

Raises:

Type Description
FileAPIError

If file modification fails, including a server rejection (top-level or nested error)

ValidationError

If parameters are invalid

Examples:

>>> updated_file = api.modify_file(
...     file_id="abc123",
...     name="updated_report.pdf",
...     expire_ts="now+3600",
...     path="/reports/2024/updated/"
... )
>>> print(f"Updated file: {updated_file}")
Source code in silo_sdk/storage/file_api.py
@api_tag(MethodType.API_COMMAND, api_command="modifyfile")
def modify_file(
    self,
    file_id: str,
    name: str | None = None,
    expire_ts: str | int | float | None = None,
    path: str | None = None,
    content_type: str | None = None,
) -> dict[str, Any]:
    """Change properties of a file by file_id in Silo storage.

    Modifies various properties of an existing file including its name,
    path, expiration time, and content type.

    Args:
        file_id: ID of the file to modify (required)
        name: New name for the file (optional)
        expire_ts: New file expiry (optional). An ``int``/``float`` is
            sent as a string. Accepted forms:

            - epoch seconds, e.g. ``1767225600``
            - ``"now+SECONDS"`` -- that long from now, e.g. ``"now+3600"``
            - ``"+SECONDS"`` -- extend the **current** expiry by that
              long; the server errors on a non-expiring file ("cannot
              extend expire time for non-expiring file")
            - ``"reset"`` -- the bucket's default expiry; errors if the
              bucket has none ("bucket has no expire time to reset to")
            - an ISO-8601 timestamp string
        path: Path of new location to move file (optional)
        content_type: New content type of modified file (optional)

    Returns:
        Dictionary containing the API response

    Raises:
        FileAPIError: If file modification fails, including a server
            rejection (top-level or nested ``error``)
        ValidationError: If parameters are invalid

    Examples:
        >>> updated_file = api.modify_file(
        ...     file_id="abc123",
        ...     name="updated_report.pdf",
        ...     expire_ts="now+3600",
        ...     path="/reports/2024/updated/"
        ... )
        >>> print(f"Updated file: {updated_file}")
    """
    if not file_id or not isinstance(file_id, str):
        raise ValidationError("File ID must be a non-empty string")

    # Build modifyfile command — setauth is injected by _make_api_request
    modify_command: dict[str, Any] = {"command": "modifyfile", "file_id": file_id}

    # Add optional parameters
    if name is not None:
        if not isinstance(name, str) or not name:
            raise ValidationError("Name must be a non-empty string")
        modify_command["name"] = name

    if expire_ts is not None:
        if isinstance(expire_ts, bool):
            # FileAPIError: a bool used to reach the server and fail there.
            raise FileAPIError("expire_ts must be a string or a number")
        # The server calls .startswith() on it, so a bare number is an
        # HTTP 500 there.
        if isinstance(expire_ts, (int, float)):
            expire_ts = str(expire_ts)
        modify_command["expire_ts"] = expire_ts

    if path is not None:
        if not isinstance(path, str):
            raise ValidationError("Path must be a string")
        modify_command["path"] = path

    if content_type is not None:
        if not isinstance(content_type, str):
            raise ValidationError("Content type must be a string")
        modify_command["content_type"] = content_type

    payload = [modify_command]

    try:
        self.logger.debug("Modifying file: %s", file_id)

        # Route through the shared request helper (like every other
        # command) instead of posting directly to the bare base_url,
        # which is missing the "api/" path segment the server expects.
        response = self._make_api_request("POST", "api/", self.auth_token, payload)

        # Check if modification was successful
        if len(response) >= 2 and isinstance(response[1], dict):
            result_entry = response[1]
            if "error" in result_entry:
                raise FileAPIError(f"API error: {result_entry['error']}")
            modify_result = result_entry.get("result")
            if isinstance(modify_result, dict) and modify_result.get("error"):
                raise FileAPIError(f"API error: {modify_result['error']}")
            if modify_result and "update file" in str(modify_result):
                self.logger.info("Successfully modified file: %s", file_id)
                return {
                    "result": modify_result,
                    "file_id": file_id,
                    "response": response,
                }

        raise FileAPIError(
            f"Unexpected response format: {self._format_response_for_log(response)}"
        )

    except Exception as e:
        if isinstance(e, FileAPIError):
            raise
        raise FileAPIError(f"Failed to modify file: {e}") from e

delete_file

delete_file(file_id: str) -> bool

Delete file in Silo storage by file_id.

Permanently deletes a file from Silo storage. This action cannot be undone.

Parameters:

Name Type Description Default
file_id str

ID of the file to delete

required

Returns:

Type Description
bool

True if deletion was successful, False otherwise

Raises:

Type Description
FileAPIError

If file deletion fails

ValidationError

If file_id is invalid

Examples:

>>> success = api.delete_file("abc123")
>>> if success:
...     print("File deleted successfully")
Source code in silo_sdk/storage/file_api.py
@api_tag(MethodType.API_COMMAND, api_command="deletefile")
def delete_file(self, file_id: str) -> bool:
    """Delete file in Silo storage by file_id.

    Permanently deletes a file from Silo storage. This action cannot be undone.

    Args:
        file_id: ID of the file to delete

    Returns:
        True if deletion was successful, False otherwise

    Raises:
        FileAPIError: If file deletion fails
        ValidationError: If file_id is invalid

    Examples:
        >>> success = api.delete_file("abc123")
        >>> if success:
        ...     print("File deleted successfully")
    """
    if not file_id or not isinstance(file_id, str):
        raise ValidationError("File ID must be a non-empty string")

    payload = [
        {
            "command": "deletefile",
            "file_id": file_id,
        }
    ]

    try:
        self.logger.debug("Deleting file: %s", file_id)
        response = self._make_api_request("POST", "api/", self.auth_token, payload)

        result = self._extract_api_result(response)
        if isinstance(result, str) and "deleted file" in result:
            self.logger.info("Successfully deleted file: %s", file_id)
            return True
        if isinstance(result, dict) and (
            result.get("deleted") or result.get("success")
        ):
            self.logger.info("Successfully deleted file: %s", file_id)
            return True

        self.logger.warning("File deletion may have failed: %s", result)
        return False

    except Exception as e:
        if isinstance(e, FileAPIError):
            raise
        raise FileAPIError(f"Failed to delete file: {e}") from e

get_file_info

get_file_info(file_id: str, bucket_id: str | None = None) -> dict[str, Any]

Get detailed information about a file.

Retrieves information about a single file by listing the bucket and matching on file_id client-side.

Warning

file_id is sent to findfiles but the platform drops it -- the handler allowlists its arguments and file_id is not among them, the same reason find_files' size bounds are applied on arrival. So this is a full listing of the bucket on every call; the server does not page, so a file in the bucket is always found. There is no scoped lookup on findfiles to use instead.

Parameters:

Name Type Description Default
file_id str

ID of the file to get information for

required
bucket_id str | None

Bucket to search in. If omitted, the configured BUCKET_ID is used.

None

Returns:

Type Description
dict[str, Any]

Dictionary containing detailed file information

Raises:

Type Description
FileAPIError

If file information retrieval fails, or no bucket is given and BUCKET_ID is not configured (the server always rejects a findfiles without one, so this is raised before any request is sent)

ValidationError

If file_id is invalid

Examples:

>>> file_info = api.get_file_info("abc123")
>>> print(f"File: {file_info['name']}")
>>> print(f"Size: {file_info['file_size']} bytes")
>>> print(f"Created: {file_info['create_ts']}")
Source code in silo_sdk/storage/file_api.py
@api_tag(MethodType.CONVENIENCE, wraps=["findfiles"])
def get_file_info(
    self, file_id: str, bucket_id: str | None = None
) -> dict[str, Any]:
    """Get detailed information about a file.

    Retrieves information about a single file by listing the bucket and
    matching on ``file_id`` client-side.

    Warning:
        ``file_id`` is sent to ``findfiles`` but the platform drops it --
        the handler allowlists its arguments and ``file_id`` is not among
        them, the same reason ``find_files``' size bounds are applied on
        arrival. So this is a **full listing of the bucket** on every
        call; the server does not page, so a file in the bucket is always
        found. There is no scoped lookup on ``findfiles`` to use instead.

    Args:
        file_id: ID of the file to get information for
        bucket_id: Bucket to search in. If omitted, the configured
            ``BUCKET_ID`` is used.

    Returns:
        Dictionary containing detailed file information

    Raises:
        FileAPIError: If file information retrieval fails, or no bucket
            is given and ``BUCKET_ID`` is not configured (the server always
            rejects a ``findfiles`` without one, so this is raised before
            any request is sent)
        ValidationError: If file_id is invalid

    Examples:
        >>> file_info = api.get_file_info("abc123")
        >>> print(f"File: {file_info['name']}")
        >>> print(f"Size: {file_info['file_size']} bytes")
        >>> print(f"Created: {file_info['create_ts']}")
    """
    if not file_id or not isinstance(file_id, str):
        raise ValidationError("File ID must be a non-empty string")

    # Use the provided bucket_id or fall back to configured bucket
    search_bucket_id = bucket_id or self._config.get("BUCKET_ID")
    if not search_bucket_id:
        # FileAPIError, not ValidationError: before 0.16.1 this case reached
        # the server and came back as FileAPIError, and callers catch that.
        raise FileAPIError(
            "bucket_id is required: pass it or set BUCKET_ID "
            "(A8_BUCKET_ID); the server rejects findfiles without one"
        )

    try:
        self.logger.debug("Getting file info for: %s", file_id)

        # file_id is sent but dropped server-side: findfiles allowlists
        # its arguments and file_id is not on the list, so the full bucket
        # listing comes back and the loop below does the matching. Left in
        # the payload because it is harmless and becomes correct for free
        # if the platform ever accepts it -- but do not read this as a
        # scoped lookup; see the Warning in the docstring.
        find_command: dict[str, Any] = {
            "command": "findfiles",
            "file_id": file_id,
        }

        find_command["bucket_id"] = search_bucket_id

        payload = [find_command]

        response = self._make_api_request("POST", "api/", self.auth_token, payload)

        # Extract results and find the matching file_id
        if len(response) >= 2 and isinstance(response[1], dict):
            result_entry = response[1]
            if "error" in result_entry:
                raise FileAPIError(f"API error: {result_entry['error']}")
            files_list = result_entry.get("result", [])
            if isinstance(files_list, dict) and files_list.get("error"):
                raise FileAPIError(f"API error: {files_list['error']}")
            if isinstance(files_list, list):
                # Find the file with matching file_id. The server-side
                # filter should already narrow this to a single entry,
                # but we still match explicitly in case the wire
                # implementation returns extra entries.
                for file_info in files_list:
                    if (
                        isinstance(file_info, dict)
                        and file_info.get("file_id") == file_id
                    ):
                        self.logger.debug("Found file information for: %s", file_id)
                        return file_info

                # File not found in this bucket
                raise FileAPIError(
                    f"File with ID {file_id} not found in bucket {search_bucket_id}"
                )

        raise FileAPIError(
            f"Unexpected response format: {self._format_response_for_log(response)}"
        )

    except Exception as e:
        if isinstance(e, FileAPIError):
            raise
        raise FileAPIError(f"Failed to get file information: {e}") from e

download_file_with_retry_async async

download_file_with_retry_async(file_id: str, output_path: str | Path, max_retries: int = 3, timeout: int = 60, create_dirs: bool = True, _client: AsyncClient | None = None) -> str

Asynchronously download file by file_id with retry mechanism. Downloads a file from Silo storage with configurable retry logic and timeout handling. This async version allows for non-blocking downloads and can be used for concurrent file downloads.

Parameters:

Name Type Description Default
file_id str

ID of the file to download

required
output_path str | Path

Path where to save the downloaded file

required
max_retries int

Positive maximum number of retry attempts (default: 3)

3
timeout int

Positive request timeout in seconds (default: 60)

60
create_dirs bool

Whether to create parent directories if they don't exist

True
_client AsyncClient | None

Internal. An open client to borrow instead of creating one, so a bulk caller can share a single connection pool across files. Not part of the public API.

None

Returns:

Type Description
str

Path of the downloaded file (as string)

Raises:

Type Description
FileAPIError

If file download fails, the server blocks the file as malware (HTTP 200 + JSON body), or the body is shorter than its Content-Length. Neither of those, nor a 500 reporting a malware scan failure, is retried.

ValidationError

If parameters are invalid

Examples:

>>> import asyncio
>>> async def download_files():
...     files = FileAPI(config)
...     downloaded_path = await files.download_file_with_retry_async(
...         file_id="abc123",
...         output_path="/home/user/downloads/report.pdf",
...         max_retries=5
...     )
...     return downloaded_path
>>> path = asyncio.run(download_files())
Source code in silo_sdk/storage/file_api.py
@api_tag(MethodType.ASYNC_VARIANT, api_command="getfile", sync_of="download_file")
async def download_file_with_retry_async(
    self,
    file_id: str,
    output_path: str | Path,
    max_retries: int = 3,
    timeout: int = 60,
    create_dirs: bool = True,
    _client: httpx.AsyncClient | None = None,
) -> str:
    """Asynchronously download file by file_id with retry mechanism.
    Downloads a file from Silo storage with configurable retry logic and
    timeout handling. This async version allows for non-blocking downloads
    and can be used for concurrent file downloads.

    Args:
        file_id: ID of the file to download
        output_path: Path where to save the downloaded file
        max_retries: Positive maximum number of retry attempts (default: 3)
        timeout: Positive request timeout in seconds (default: 60)
        create_dirs: Whether to create parent directories if they don't exist
        _client: Internal. An open client to borrow instead of creating one,
            so a bulk caller can share a single connection pool across
            files. Not part of the public API.

    Returns:
        Path of the downloaded file (as string)

    Raises:
        FileAPIError: If file download fails, the server blocks the file
            as malware (HTTP 200 + JSON body), or the body is shorter than
            its Content-Length. Neither of those, nor a 500 reporting a
            malware scan failure, is retried.
        ValidationError: If parameters are invalid

    Examples:
        >>> import asyncio
        >>> async def download_files():
        ...     files = FileAPI(config)
        ...     downloaded_path = await files.download_file_with_retry_async(
        ...         file_id="abc123",
        ...         output_path="/home/user/downloads/report.pdf",
        ...         max_retries=5
        ...     )
        ...     return downloaded_path
        >>> path = asyncio.run(download_files())
    """
    validate_positive_int(max_retries, "max_retries")
    validate_positive_int(timeout, "timeout")

    if not file_id or not isinstance(file_id, str):
        raise ValidationError("File ID must be a non-empty string")

    if not output_path:
        raise ValidationError("Output path must be provided")

    # Convert to Path object
    output_path = Path(output_path)

    try:
        self.logger.debug(
            "Starting async download with retry for file ID: %s", file_id
        )

        await self._prepare_output_dir_async(output_path, create_dirs)

        download_url = f"{self.base_url.rstrip('/')}/getfile/"

        async with self._client_scope(_client) as client:
            for attempt in range(max_retries):
                self.logger.debug(
                    f"Download attempt {attempt + 1} for file {file_id}"
                )
                try:
                    response = await client.post(
                        download_url,
                        data={"id": file_id, "auth": self.auth_token},
                        timeout=httpx.Timeout(timeout),
                    )
                    response.raise_for_status()
                    content = response.content

                    # Malware block: HTTP 200 + JSON, not the file. Raised
                    # outside the retry handler (not an httpx error) and
                    # before anything is written.
                    if _is_json_response(response):
                        blocked = _malware_error(content)
                        if blocked is not None:
                            raise blocked

                    expected = _expected_length(response)
                    if expected is not None and len(content) < expected:
                        raise _short_body_error(expected, len(content))

                    # Opening and writing both block; Path.write_bytes does
                    # all of it inside the worker thread so the event loop
                    # stays free for the other downloads in a bulk run.
                    try:
                        await asyncio.to_thread(output_path.write_bytes, content)
                    except OSError as write_error:
                        # write_bytes opens "wb", so it has already
                        # truncated whatever was at output_path before it
                        # failed. Retrying will not help a full disk or a
                        # revoked permission, and the sibling methods both
                        # clean up here -- leaving the remnant is what lets
                        # a caller mistake it for a complete download.
                        await asyncio.to_thread(
                            self._cleanup_partial_file, output_path
                        )
                        raise FileAPIError(
                            f"Failed to write downloaded file to "
                            f"{output_path}: {write_error}"
                        ) from write_error

                    self.logger.info(
                        "Successfully downloaded file to: %s", output_path
                    )
                    return str(output_path)

                except httpx.HTTPError as e:
                    self.logger.error(
                        f"Error downloading file (attempt {attempt + 1}/{max_retries}): {e}"
                    )
                    if not _is_retryable(e):
                        raise (
                            _short_body_defect(e)
                            or FileAPIError(
                                f"Failed to download file: {e}{_status_suffix(e)}"
                            )
                        ) from e
                    if attempt == max_retries - 1:
                        raise FileAPIError(
                            f"Failed to download file after {max_retries} "
                            f"attempts: {e}{_status_suffix(e)}"
                        ) from e
                    await asyncio.sleep(_retry_delay(e, attempt))

        # If we get here, all retries were exhausted without success
        raise FileAPIError(
            f"Failed to download file after {max_retries} attempts"
        )  # pragma: no cover

    except Exception as e:  # pragma: no cover
        if isinstance(e, FileAPIError):
            raise
        raise FileAPIError(f"Failed to download file with retry: {e}") from e

download_file_chunked_async async

download_file_chunked_async(file_id: str, output_path: str | Path, chunk_size: int = 8192, timeout: int = 60, create_dirs: bool = True, _client: AsyncClient | None = None) -> str

Asynchronously download file by file_id using chunked download. Downloads a file from Silo storage using streaming/chunked approach, which is more memory-efficient for large files. This async version allows for non-blocking downloads of large files.

Parameters:

Name Type Description Default
file_id str

ID of the file to download

required
output_path str | Path

Path where to save the downloaded file

required
chunk_size int

Positive size of chunks to read at a time (default: 8192)

8192
timeout int

Positive request timeout in seconds (default: 60)

60
create_dirs bool

Whether to create parent directories if they don't exist

True
_client AsyncClient | None

Internal. An open client to borrow instead of creating one, so a bulk caller can share a single connection pool across files. Not part of the public API.

None

Returns:

Type Description
str

Path of the downloaded file (as string)

Raises:

Type Description
FileAPIError

If file download fails, the server blocks the file as malware (HTTP 200 + JSON body; no output file is created), or the body is shorter than its Content-Length (the partial file is removed).

ValidationError

If parameters are invalid

Examples:

>>> import asyncio
>>> async def download_large_file():
...     files = FileAPI(config)
...     downloaded_path = await files.download_file_chunked_async(
...         file_id="large_file_123",
...         output_path="/home/user/downloads/large_archive.zip",
...         chunk_size=16384
...     )
...     return downloaded_path
>>> path = asyncio.run(download_large_file())
Source code in silo_sdk/storage/file_api.py
@api_tag(MethodType.ASYNC_VARIANT, api_command="getfile", sync_of="download_file")
async def download_file_chunked_async(
    self,
    file_id: str,
    output_path: str | Path,
    chunk_size: int = 8192,
    timeout: int = 60,
    create_dirs: bool = True,
    _client: httpx.AsyncClient | None = None,
) -> str:
    """Asynchronously download file by file_id using chunked download.
    Downloads a file from Silo storage using streaming/chunked approach,
    which is more memory-efficient for large files. This async version
    allows for non-blocking downloads of large files.

    Args:
        file_id: ID of the file to download
        output_path: Path where to save the downloaded file
        chunk_size: Positive size of chunks to read at a time (default: 8192)
        timeout: Positive request timeout in seconds (default: 60)
        create_dirs: Whether to create parent directories if they don't exist
        _client: Internal. An open client to borrow instead of creating one,
            so a bulk caller can share a single connection pool across
            files. Not part of the public API.

    Returns:
        Path of the downloaded file (as string)

    Raises:
        FileAPIError: If file download fails, the server blocks the file
            as malware (HTTP 200 + JSON body; no output file is created),
            or the body is shorter than its Content-Length (the partial
            file is removed).
        ValidationError: If parameters are invalid

    Examples:
        >>> import asyncio
        >>> async def download_large_file():
        ...     files = FileAPI(config)
        ...     downloaded_path = await files.download_file_chunked_async(
        ...         file_id="large_file_123",
        ...         output_path="/home/user/downloads/large_archive.zip",
        ...         chunk_size=16384
        ...     )
        ...     return downloaded_path
        >>> path = asyncio.run(download_large_file())
    """
    validate_positive_int(chunk_size, "chunk_size")
    validate_positive_int(timeout, "timeout")

    if not file_id or not isinstance(file_id, str):
        raise ValidationError("File ID must be a non-empty string")

    if not output_path:
        raise ValidationError("Output path must be provided")

    # Convert to Path object
    output_path = Path(output_path)

    try:
        self.logger.debug(
            "Starting async chunked download for file ID: %s", file_id
        )

        await self._prepare_output_dir_async(output_path, create_dirs)

        download_url = f"{self.base_url.rstrip('/')}/getfile/"

        async with self._client_scope(_client) as client:
            try:
                async with client.stream(
                    "POST",
                    download_url,
                    data={"id": file_id, "auth": self.auth_token},
                    timeout=httpx.Timeout(timeout),
                ) as response:
                    try:
                        response.raise_for_status()
                    except httpx.HTTPStatusError:
                        # Streamed body is unread; load it so the error
                        # can carry the server's reason.
                        try:
                            await response.aread()
                        except httpx.HTTPError:
                            pass
                        raise

                    # Malware block: HTTP 200 + JSON instead of the file.
                    # Checked before the output file is opened, so nothing
                    # is created. A genuine JSON body is already buffered
                    # by aread() and still streams out below.
                    if _is_json_response(response):
                        await response.aread()
                        blocked = _malware_error(response.content)
                        if blocked is not None:
                            raise blocked

                    expected = _expected_length(response)
                    received = 0

                    try:
                        # open() and close() block exactly as the writes
                        # do, so they go to a thread too -- they were the
                        # last inline filesystem calls left in this method
                        # after the chunk writes were offloaded, and an
                        # offload that skips them still stalls the loop
                        # once per download. Hence the explicit
                        # open/try/finally rather than a `with`: the close
                        # has to be awaited.
                        f = await asyncio.to_thread(open, output_path, "wb")
                        try:
                            # Accumulate then offload. Writing each chunk
                            # inline blocked the event loop on disk for
                            # every 8 KiB of every concurrent download,
                            # which is exactly the stall streaming
                            # concurrently is supposed to avoid.
                            buffer = bytearray()
                            async for chunk in response.aiter_bytes(chunk_size):
                                received += len(chunk)
                                buffer += chunk
                                if len(buffer) >= _WRITE_BUFFER_BYTES:
                                    await asyncio.to_thread(f.write, bytes(buffer))
                                    buffer.clear()
                            if buffer:
                                await asyncio.to_thread(f.write, bytes(buffer))
                        finally:
                            await asyncio.to_thread(f.close)
                        if expected is not None and received < expected:
                            raise _short_body_error(expected, received)
                    except Exception:
                        # The finally above has closed the file by now
                        # (and if open() itself failed there is nothing
                        # to close), so this only ever unlinks a closed
                        # path. unlink blocks like any other filesystem
                        # call, so it goes to a thread for the same
                        # reason the writes do -- and to match the retry
                        # variant.
                        await asyncio.to_thread(
                            self._cleanup_partial_file, output_path
                        )
                        raise

                    self.logger.info(
                        "Successfully downloaded file to: %s", output_path
                    )
                    return str(output_path)

            except httpx.HTTPError as e:
                raise (
                    _short_body_defect(e)
                    or FileAPIError(
                        f"Failed to download file: {e}{_status_suffix(e)}"
                    )
                ) from e

    except Exception as e:
        if isinstance(e, FileAPIError):
            raise
        raise FileAPIError(f"Failed to download file chunked: {e}") from e

bulk_download_async async

bulk_download_async(file_downloads: list[dict[str, Any]], max_concurrent: int = 5, use_chunked: bool = False) -> list[str | None]

Download multiple files concurrently.

Downloads multiple files in parallel with configurable concurrency limits to efficiently handle bulk file downloads.

Parameters:

Name Type Description Default
file_downloads list[dict[str, Any]]

List of download dictionaries, each containing: - file_id: ID of the file to download - output_path: Path where to save the file - max_retries: Optional max retries (default: 3) - timeout: Optional timeout (default: 60) - chunk_size: Optional chunk size for chunked downloads

required
max_concurrent int

Positive maximum number of concurrent downloads (default: 5), up to _MAX_BULK_CONCURRENCY. The batch's shared connection pool is sized to match.

5
use_chunked bool

Which per-file download to run (default: False). The two differ in more than chunk size, so the choice is a trade-off rather than a tuning knob:

  • False — download_file_with_retry_async: retries transient failures, but buffers each response body in memory before writing. Peak memory is roughly max_concurrent × largest file.
  • True — download_file_chunked_async: streams to disk so memory stays bounded regardless of file size, but has no retry loop — a dropped connection fails that file and returns None for it.

Prefer True for large files, and re-issue the failures yourself; prefer the default when files are small enough to buffer and you would rather the SDK absorb a flaky network.

False

Returns:

Type Description
list[str | None]

List of downloaded file paths (same order as input), None for failed downloads

Raises:

Type Description
ValidationError

If parameters are invalid

Examples:

>>> import asyncio
>>> async def bulk_download():
...     files = FileAPI(config)
...     downloads = [
...         {"file_id": "file1", "output_path": "./downloads/file1.pdf"},
...         {"file_id": "file2", "output_path": "./downloads/file2.zip"},
...     ]
...     results = await files.bulk_download_async(
...         file_downloads=downloads,
...         max_concurrent=3
...     )
...     return results
>>> results = asyncio.run(bulk_download())
Source code in silo_sdk/storage/file_api.py
@api_tag(
    MethodType.ASYNC_CONVENIENCE,
    wraps=["download_file_with_retry_async", "download_file_chunked_async"],
)
async def bulk_download_async(
    self,
    file_downloads: list[dict[str, Any]],
    max_concurrent: int = 5,
    use_chunked: bool = False,
) -> list[str | None]:
    """Download multiple files concurrently.

    Downloads multiple files in parallel with configurable concurrency
    limits to efficiently handle bulk file downloads.

    Args:
        file_downloads: List of download dictionaries, each containing:
            - file_id: ID of the file to download
            - output_path: Path where to save the file
            - max_retries: Optional max retries (default: 3)
            - timeout: Optional timeout (default: 60)
            - chunk_size: Optional chunk size for chunked downloads
        max_concurrent: Positive maximum number of concurrent downloads
            (default: 5), up to ``_MAX_BULK_CONCURRENCY``. The batch's
            shared connection pool is sized to match.
        use_chunked: Which per-file download to run (default: ``False``).
            The two differ in more than chunk size, so the choice is a
            trade-off rather than a tuning knob:

            - ``False`` — ``download_file_with_retry_async``: retries
                transient failures, but buffers each response body in
                memory before writing. Peak memory is roughly
                ``max_concurrent`` × largest file.
            - ``True`` — ``download_file_chunked_async``: streams to disk
                so memory stays bounded regardless of file size, but has
                **no retry loop** — a dropped connection fails that file
                and returns ``None`` for it.

            Prefer ``True`` for large files, and re-issue the failures
            yourself; prefer the default when files are small enough to
            buffer and you would rather the SDK absorb a flaky network.

    Returns:
        List of downloaded file paths (same order as input), None for failed downloads

    Raises:
        ValidationError: If parameters are invalid

    Examples:
        >>> import asyncio
        >>> async def bulk_download():
        ...     files = FileAPI(config)
        ...     downloads = [
        ...         {"file_id": "file1", "output_path": "./downloads/file1.pdf"},
        ...         {"file_id": "file2", "output_path": "./downloads/file2.zip"},
        ...     ]
        ...     results = await files.bulk_download_async(
        ...         file_downloads=downloads,
        ...         max_concurrent=3
        ...     )
        ...     return results
        >>> results = asyncio.run(bulk_download())
    """
    validate_positive_int(max_concurrent, "max_concurrent")
    if max_concurrent > _MAX_BULK_CONCURRENCY:
        raise ValidationError(
            f"max_concurrent must be at most {_MAX_BULK_CONCURRENCY}"
        )

    # Create semaphore to limit concurrent downloads
    semaphore = asyncio.Semaphore(max_concurrent)

    async def download_single_file(
        download_config: dict[str, Any],
        client: httpx.AsyncClient,
    ) -> str | None:
        """Download a single file with semaphore control."""
        async with semaphore:
            try:
                file_id = download_config["file_id"]
                output_path = download_config["output_path"]
                max_retries = download_config.get("max_retries", 3)
                timeout = download_config.get("timeout", 60)

                if use_chunked:
                    chunk_size = download_config.get("chunk_size", 8192)
                    return await self.download_file_chunked_async(
                        file_id=file_id,
                        output_path=output_path,
                        chunk_size=chunk_size,
                        timeout=timeout,
                        _client=client,
                    )
                else:
                    return await self.download_file_with_retry_async(
                        file_id=file_id,
                        output_path=output_path,
                        max_retries=max_retries,
                        timeout=timeout,
                        _client=client,
                    )
            except Exception as e:
                self.logger.error(
                    f"Failed to download {download_config.get('file_id')}: {e}"
                )
                return None

    # Process all downloads concurrently. One client for the whole batch:
    # the per-download methods accept it rather than each opening their
    # own, so the batch shares a single connection pool instead of paying
    # a TLS handshake per file. The pool is sized to the semaphore so the
    # two agree -- httpx's default keepalive of 20 would otherwise close
    # and reopen connections underneath a wider batch.
    self.logger.info(f"Starting bulk download of {len(file_downloads)} files")
    async with httpx.AsyncClient(
        verify=self._ssl_context,
        limits=httpx.Limits(
            max_connections=max_concurrent,
            max_keepalive_connections=max_concurrent,
        ),
    ) as client:
        results = await asyncio.gather(
            *[
                download_single_file(download, client)
                for download in file_downloads
            ],
            return_exceptions=True,
        )

    # Convert exceptions to None and log errors
    processed_results: list[str | None] = []
    for i, result in enumerate(results):
        if isinstance(result, Exception):
            self.logger.error(f"Download {i + 1} failed with exception: {result}")
            processed_results.append(None)
        elif isinstance(result, str):
            processed_results.append(result)
        else:
            processed_results.append(None)

    successful_downloads = sum(1 for r in processed_results if r is not None)
    self.logger.info(
        f"Completed bulk download: {successful_downloads}/{len(file_downloads)} "
        "files successful"
    )

    return processed_results