Skip to content

Commit 0a0373f

Browse files
author
Faxbot Agent
committed
p5(p0): replace blocking file IO in sinch_service with anyio.open_file for async correctness
1 parent ffbc697 commit 0a0373f

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

api/app/sinch_service.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import logging
44
import os
55
import time
6+
import anyio
67

78
from .config import settings, reload_settings
89

@@ -80,7 +81,9 @@ async def upload_file(self, file_path: str) -> int:
8081
url = f"{base}/projects/{self.project_id}/files"
8182
try:
8283
async with httpx.AsyncClient(timeout=60.0) as client:
83-
files = {"file": (os.path.basename(file_path), open(file_path, "rb"), "application/pdf")}
84+
async with await anyio.open_file(file_path, 'rb') as f:
85+
content = await f.read()
86+
files = {"file": (os.path.basename(file_path), content, "application/pdf")}
8487
if self._use_oauth():
8588
try:
8689
token = await self.get_access_token()
@@ -154,20 +157,21 @@ async def send_fax_file(self, to_number: str, file_path: str) -> Dict[str, Any]:
154157
to = f"+{digits}"
155158
url = f"{self.base_url}/projects/{self.project_id}/faxes"
156159
async with httpx.AsyncClient(timeout=60.0) as client:
157-
# httpx expects a mapping of field name → (filename, fileobj, content_type)
160+
# httpx expects a mapping of field name → (filename, bytes, content_type)
158161
# For the additional text field, pass as data not files
159-
with open(file_path, "rb") as fh:
160-
files = {"file": (os.path.basename(file_path), fh, "application/pdf")}
161-
data = {"to": to}
162-
if self._use_oauth():
163-
try:
164-
token = await self.get_access_token()
165-
resp = await client.post(url, files=files, data=data, headers={"Authorization": f"Bearer {token}"})
166-
except Exception as e:
167-
logger.warning("Sinch OAuth send_fax_file failed; falling back to Basic: %s", e)
168-
resp = await client.post(url, files=files, data=data, auth=self._basic_auth())
169-
else:
162+
async with await anyio.open_file(file_path, 'rb') as fh:
163+
content = await fh.read()
164+
files = {"file": (os.path.basename(file_path), content, "application/pdf")}
165+
data = {"to": to}
166+
if self._use_oauth():
167+
try:
168+
token = await self.get_access_token()
169+
resp = await client.post(url, files=files, data=data, headers={"Authorization": f"Bearer {token}"})
170+
except Exception as e:
171+
logger.warning("Sinch OAuth send_fax_file failed; falling back to Basic: %s", e)
170172
resp = await client.post(url, files=files, data=data, auth=self._basic_auth())
173+
else:
174+
resp = await client.post(url, files=files, data=data, auth=self._basic_auth())
171175
if resp.status_code >= 400:
172176
raise RuntimeError(f"Sinch create fax error {resp.status_code}: {resp.text}")
173177
return resp.json()

0 commit comments

Comments
 (0)