Skip to content

Commit 1b81071

Browse files
odesenfanshoh
authored andcommitted
[Types] Use ItemType defined in aleph-message
Removed the `ItemType` enum and replaced all usages by the equivalent class in aleph-message.
1 parent ac554c1 commit 1b81071

File tree

9 files changed

+65
-70
lines changed

9 files changed

+65
-70
lines changed

src/aleph/handlers/forget.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
import logging
2-
from typing import Dict, Optional
2+
from typing import Dict
33

44
from aioipfs.api import RepoAPI
55
from aioipfs.exceptions import NotPinnedError
6-
from aleph_message.models import ForgetMessage, MessageType
6+
from aleph_message.models import ForgetMessage, ItemType, MessageType, StoreContent
77

88
from aleph.model.filepin import PermanentPin
9-
from aleph_message.models import StoreContent
109
from aleph.model.hashes import delete_value
1110
from aleph.model.messages import Message
1211
from aleph.services.ipfs.common import get_ipfs_api
1312
from aleph.storage import get_message_content
14-
from aleph.types import ItemType
13+
from aleph.utils import item_type_from_hash
1514

1615
logger = logging.getLogger(__name__)
1716

@@ -47,13 +46,13 @@ async def garbage_collect(storage_hash: str, storage_type: ItemType):
4746
return
4847

4948
# Unpin the file from IPFS or remove it from local storage
50-
storage_detected: ItemType = ItemType.from_hash(storage_hash)
49+
storage_detected: ItemType = item_type_from_hash(storage_hash)
5150

5251
if storage_type != storage_detected:
5352
raise ValueError(f"Inconsistent ItemType {storage_type} != {storage_detected} "
5453
f"for hash '{storage_hash}'")
5554

56-
if storage_type == ItemType.IPFS:
55+
if storage_type == ItemType.ipfs:
5756
api = await get_ipfs_api(timeout=5)
5857
logger.debug(f"Removing from IPFS: {storage_hash}")
5958
try:
@@ -67,7 +66,7 @@ async def garbage_collect(storage_hash: str, storage_type: ItemType):
6766
except NotPinnedError:
6867
logger.debug("File not pinned")
6968
logger.debug(f"Removed from IPFS: {storage_hash}")
70-
elif storage_type == ItemType.Storage:
69+
elif storage_type == ItemType.storage:
7170
logger.debug(f"Removing from Gridfs: {storage_hash}")
7271
await delete_value(storage_hash)
7372
logger.debug(f"Removed from Gridfs: {storage_hash}")

src/aleph/handlers/storage.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,14 @@
1414

1515
import aioipfs
1616
from aioipfs import InvalidCIDError
17+
from aleph_message.models import ItemType, StoreMessage
18+
from pydantic import ValidationError
19+
1720
from aleph.config import get_config
1821
from aleph.exceptions import AlephStorageException, UnknownHashError
1922
from aleph.services.ipfs.common import get_ipfs_api
2023
from aleph.storage import get_hash_content
21-
from aleph.types import ItemType
22-
from aleph_message.models import StoreMessage
23-
from pydantic import ValidationError
24+
from aleph.utils import item_type_from_hash
2425

2526
LOGGER = logging.getLogger("HANDLERS.STORAGE")
2627

@@ -52,8 +53,8 @@ async def handle_new_storage(message: Dict, content: Dict):
5253
do_standard_lookup = True
5354
size = 0
5455

55-
if engine == ItemType.IPFS and ipfs_enabled:
56-
if ItemType.from_hash(item_hash) != ItemType.IPFS:
56+
if engine == ItemType.ipfs and ipfs_enabled:
57+
if item_type_from_hash(item_hash) != ItemType.ipfs:
5758
LOGGER.warning("Invalid IPFS hash: '%s'", item_hash)
5859
raise UnknownHashError(f"Invalid IPFS hash: '{item_hash}'")
5960

src/aleph/jobs/process_pending_messages.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from typing import List, Dict, Tuple
99

1010
import sentry_sdk
11-
from aleph_message.models import MessageType
11+
from aleph_message.models import ItemType, MessageType
1212
from pymongo import DeleteOne, DeleteMany, ASCENDING
1313
from setproctitle import setproctitle
1414

@@ -17,7 +17,6 @@
1717
from aleph.model.db_bulk_operation import DbBulkOperation
1818
from aleph.model.pending import PendingMessage
1919
from aleph.services.p2p import singleton
20-
from aleph.types import ItemType
2120
from .job_utils import prepare_loop, gather_and_perform_db_operations
2221

2322
LOGGER = getLogger("jobs.pending_messages")
@@ -94,7 +93,7 @@ async def process_pending_messages(shared_stats: Dict):
9493
)
9594

9695
if (
97-
pending["message"]["item_type"] == ItemType.IPFS
96+
pending["message"]["item_type"] == ItemType.ipfs
9897
or pending["message"]["type"] == MessageType.store
9998
):
10099
i += 15

src/aleph/network.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
import asyncio
22
import json
33
import logging
4-
from typing import Coroutine, Dict, List, Optional
4+
from typing import Coroutine, Dict, List
55
from urllib.parse import unquote
66

7+
from aleph_message.models import ItemType
78
from p2pclient import Client as P2PClient
89

10+
from aleph.exceptions import InvalidMessageError
911
from aleph.register_chain import VERIFIER_REGISTER
1012
from aleph.services.ipfs.pubsub import incoming_channel as incoming_ipfs_channel
11-
from aleph.types import ItemType
12-
from aleph.exceptions import InvalidMessageError
1313
from aleph.utils import get_sha256
14+
from aleph.utils import item_type_from_hash
1415

1516
LOGGER = logging.getLogger("NETWORK")
1617

@@ -116,11 +117,11 @@ async def check_message(
116117
else:
117118
raise InvalidMessageError("Unknown hash type %s" % message["hash_type"])
118119

119-
message["item_type"] = ItemType.Inline.value
120+
message["item_type"] = ItemType.inline.value
120121

121122
else:
122123
try:
123-
message["item_type"] = ItemType.from_hash(message["item_hash"]).value
124+
message["item_type"] = item_type_from_hash(message["item_hash"]).value
124125
except ValueError as error:
125126
LOGGER.warning(error)
126127

src/aleph/storage.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,19 @@
99
from hashlib import sha256
1010
from typing import Any, AnyStr, Dict, IO, Optional
1111

12+
from aleph_message.models import ItemType
13+
14+
from aleph.config import get_config
1215
from aleph.exceptions import InvalidContent, ContentCurrentlyUnavailable
1316
from aleph.services.filestore import get_value, set_value
17+
from aleph.services.ipfs.common import get_cid_version
1418
from aleph.services.ipfs.storage import add_bytes as add_ipfs_bytes
1519
from aleph.services.ipfs.storage import add_file as ipfs_add_file
1620
from aleph.services.ipfs.storage import get_ipfs_content
1721
from aleph.services.ipfs.storage import pin_add as ipfs_pin_add
1822
from aleph.services.p2p.http import request_hash as p2p_http_request_hash
1923
from aleph.services.p2p.singleton import get_streamer
20-
from aleph.types import ItemType
21-
from aleph.utils import run_in_executor, get_sha256
22-
from aleph.services.ipfs.common import get_cid_version
23-
from aleph.config import get_config
24+
from aleph.utils import get_sha256, run_in_executor
2425

2526
LOGGER = logging.getLogger("STORAGE")
2627

@@ -66,12 +67,12 @@ async def json_async_loads(s: AnyStr):
6667

6768

6869
async def get_message_content(message: Dict) -> MessageContent:
69-
item_type: str = message.get("item_type", ItemType.IPFS)
70+
item_type: str = message.get("item_type", ItemType.ipfs)
7071
item_hash = message["item_hash"]
7172

72-
if item_type in (ItemType.IPFS, ItemType.Storage):
73+
if item_type in (ItemType.ipfs, ItemType.storage):
7374
return await get_json(item_hash, engine=ItemType(item_type))
74-
elif item_type == ItemType.Inline:
75+
elif item_type == ItemType.inline:
7576
if "item_content" not in message:
7677
error_msg = f"No item_content in message {message.get('item_hash')}"
7778
LOGGER.warning(error_msg)
@@ -149,13 +150,13 @@ async def verify_content_hash(
149150
config = get_config()
150151
ipfs_enabled = config.ipfs.enabled.value
151152

152-
if engine == ItemType.IPFS and ipfs_enabled:
153+
if engine == ItemType.ipfs and ipfs_enabled:
153154
try:
154155
cid_version = get_cid_version(expected_hash)
155156
except ValueError as e:
156157
raise InvalidContent(e) from e
157158
compute_hash_task = compute_content_hash_ipfs(content, cid_version)
158-
elif engine == ItemType.Storage:
159+
elif engine == ItemType.storage:
159160
compute_hash_task = compute_content_hash_sha256(content)
160161
else:
161162
raise ValueError(f"Invalid storage engine: '{engine}'.")
@@ -175,7 +176,7 @@ async def verify_content_hash(
175176

176177
async def get_hash_content(
177178
content_hash: str,
178-
engine: ItemType = ItemType.IPFS,
179+
engine: ItemType = ItemType.ipfs,
179180
timeout: int = 2,
180181
tries: int = 1,
181182
use_network: bool = True,
@@ -198,7 +199,7 @@ async def get_hash_content(
198199
source = ContentSource.P2P
199200

200201
if content is None:
201-
if ipfs_enabled and engine == ItemType.IPFS and use_ipfs:
202+
if ipfs_enabled and engine == ItemType.ipfs and use_ipfs:
202203
content = await get_ipfs_content(content_hash, timeout=timeout, tries=tries)
203204
source = ContentSource.IPFS
204205

@@ -218,7 +219,7 @@ async def get_hash_content(
218219

219220

220221
async def get_json(
221-
content_hash: str, engine=ItemType.IPFS, timeout: int = 2, tries: int = 1
222+
content_hash: str, engine=ItemType.ipfs, timeout: int = 2, tries: int = 1
222223
) -> MessageContent:
223224
content = await get_hash_content(
224225
content_hash, engine=engine, timeout=timeout, tries=tries
@@ -242,13 +243,13 @@ async def pin_hash(chash: str, timeout: int = 2, tries: int = 1):
242243
return await ipfs_pin_add(chash, timeout=timeout, tries=tries)
243244

244245

245-
async def add_json(value: Any, engine: ItemType = ItemType.IPFS) -> str:
246+
async def add_json(value: Any, engine: ItemType = ItemType.ipfs) -> str:
246247
# TODO: determine which storage engine to use
247248
content = await run_in_executor(None, json.dumps, value)
248249
content = content.encode("utf-8")
249-
if engine == ItemType.IPFS:
250+
if engine == ItemType.ipfs:
250251
chash = await add_ipfs_bytes(content)
251-
elif engine == ItemType.Storage:
252+
elif engine == ItemType.storage:
252253
if isinstance(content, str):
253254
content = content.encode("utf-8")
254255
chash = sha256(content).hexdigest()
@@ -259,15 +260,15 @@ async def add_json(value: Any, engine: ItemType = ItemType.IPFS) -> str:
259260
return chash
260261

261262

262-
async def add_file(fileobject: IO, engine: ItemType = ItemType.IPFS) -> str:
263+
async def add_file(fileobject: IO, engine: ItemType = ItemType.ipfs) -> str:
263264

264-
if engine == ItemType.IPFS:
265+
if engine == ItemType.ipfs:
265266
output = await ipfs_add_file(fileobject)
266267
file_hash = output["Hash"]
267268
fileobject.seek(0)
268269
file_content = fileobject.read()
269270

270-
elif engine == ItemType.Storage:
271+
elif engine == ItemType.storage:
271272
file_content = fileobject.read()
272273
file_hash = sha256(file_content).hexdigest()
273274

src/aleph/types.py

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,6 @@
11
from __future__ import annotations
2-
from enum import Enum
3-
4-
from aleph.exceptions import UnknownHashError
5-
62

7-
class ItemType(str, Enum):
8-
"""Item storage options"""
9-
Inline = "inline"
10-
IPFS = "ipfs"
11-
Storage = "storage"
12-
13-
@classmethod
14-
def from_hash(cls, hash: str) -> ItemType:
15-
assert isinstance(hash, str)
16-
# https://docs.ipfs.io/concepts/content-addressing/#identifier-formats
17-
if hash.startswith("Qm") and 44 <= len(hash) <= 46: # CIDv0
18-
return cls.IPFS
19-
elif hash.startswith("bafy") and len(hash) == 59: # CIDv1
20-
return cls.IPFS
21-
elif len(hash) == 64:
22-
return cls.Storage
23-
else:
24-
raise UnknownHashError(f"Unknown hash {len(hash)} {hash}")
3+
from enum import Enum
254

265

276
class Protocol(str, Enum):

src/aleph/utils.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
from hashlib import sha256
33
from typing import Union
44

5+
from aleph_message.models import ItemType
6+
7+
from aleph.exceptions import UnknownHashError
58
from aleph.settings import settings
69

710

@@ -13,6 +16,18 @@ async def run_in_executor(executor, func, *args):
1316
return func(*args)
1417

1518

19+
def item_type_from_hash(item_hash: str) -> ItemType:
20+
# https://docs.ipfs.io/concepts/content-addressing/#identifier-formats
21+
if item_hash.startswith("Qm") and 44 <= len(item_hash) <= 46: # CIDv0
22+
return ItemType.ipfs
23+
elif item_hash.startswith("bafy") and len(item_hash) == 59: # CIDv1
24+
return ItemType.ipfs
25+
elif len(item_hash) == 64:
26+
return ItemType.storage
27+
else:
28+
raise UnknownHashError(f"Unknown hash {len(item_hash)} {item_hash}")
29+
30+
1631
def get_sha256(content: Union[str, bytes]) -> str:
1732
if isinstance(content, str):
1833
content = content.encode("utf-8")

src/aleph/web/controllers/storage.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
from aleph.exceptions import AlephStorageException, UnknownHashError
77
from aleph.handlers.forget import count_file_references
88
from aleph.storage import add_json, get_hash_content, add_file
9-
from aleph.types import ItemType
10-
from aleph.utils import run_in_executor
9+
from aleph_message.models import ItemType
10+
from aleph.utils import run_in_executor, item_type_from_hash
1111

1212
logger = logging.getLogger(__name__)
1313

@@ -16,23 +16,23 @@ async def add_ipfs_json_controller(request):
1616
"""Forward the json content to IPFS server and return an hash"""
1717
data = await request.json()
1818

19-
output = {"status": "success", "hash": await add_json(data, engine=ItemType.IPFS)}
19+
output = {"status": "success", "hash": await add_json(data, engine=ItemType.ipfs)}
2020
return web.json_response(output)
2121

2222

2323
async def add_storage_json_controller(request):
2424
"""Forward the json content to IPFS server and return an hash"""
2525
data = await request.json()
2626

27-
output = {"status": "success", "hash": await add_json(data, engine=ItemType.Storage)}
27+
output = {"status": "success", "hash": await add_json(data, engine=ItemType.storage)}
2828
return web.json_response(output)
2929

3030

3131
async def storage_add_file(request):
3232
# No need to pin it here anymore.
3333
# TODO: find a way to specify linked ipfs hashes in posts/aggr.
3434
post = await request.post()
35-
file_hash = await add_file(post["file"].file, engine=ItemType.Storage)
35+
file_hash = await add_file(post["file"].file, engine=ItemType.storage)
3636

3737
output = {"status": "success", "hash": file_hash}
3838
return web.json_response(output)
@@ -47,7 +47,7 @@ async def get_hash(request):
4747
if item_hash is None:
4848
return web.HTTPBadRequest(text="No hash provided")
4949
try:
50-
engine = ItemType.from_hash(item_hash)
50+
engine = item_type_from_hash(item_hash)
5151
except UnknownHashError as e:
5252
logger.warning(e.args[0])
5353
return web.HTTPBadRequest(text="Invalid hash provided")
@@ -83,7 +83,7 @@ async def get_raw_hash(request):
8383
raise web.HTTPBadRequest(text="No hash provided")
8484

8585
try:
86-
engine = ItemType.from_hash(item_hash)
86+
engine = item_type_from_hash(item_hash)
8787
except UnknownHashError:
8888
raise web.HTTPBadRequest(text="Invalid hash")
8989

tests/storage/test_get_content.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from aleph.exceptions import InvalidContent, ContentCurrentlyUnavailable
66
from aleph.storage import ContentSource, get_hash_content, get_json, get_message_content
7-
from aleph.types import ItemType
7+
from aleph_message.models import ItemType
88

99

1010
@pytest.mark.asyncio
@@ -139,7 +139,7 @@ async def test_get_inline_content(mock_config):
139139
]
140140
json_bytes = json.dumps(json_content).encode("utf-8")
141141
message = {
142-
"item_type": ItemType.Inline.value,
142+
"item_type": ItemType.inline.value,
143143
"item_hash": content_hash,
144144
"item_content": json_bytes,
145145
}
@@ -185,7 +185,7 @@ async def test_get_stored_message_content(mocker, mock_config):
185185
mocker.patch("aleph.storage.get_value", return_value=json_bytes)
186186

187187
message = {
188-
"item_type": ItemType.IPFS.value,
188+
"item_type": ItemType.ipfs.value,
189189
"item_hash": content_hash,
190190
}
191191

0 commit comments

Comments
 (0)