refactor(deltachat-rpc-client): use itertools for thread-safe request ID generation

This commit is contained in:
link2xt
2023-11-08 00:13:06 +00:00
parent 0c2276775d
commit 620e363ce6

View File

@@ -1,11 +1,12 @@
import itertools
import json import json
import logging import logging
import os import os
import subprocess import subprocess
import sys import sys
from queue import Queue from queue import Queue
from threading import Event, Lock, Thread from threading import Event, Thread
from typing import Any, Dict, Optional from typing import Any, Dict, Iterator, Optional
class JsonRpcError(Exception): class JsonRpcError(Exception):
@@ -23,8 +24,7 @@ class Rpc:
self._kwargs = kwargs self._kwargs = kwargs
self.process: subprocess.Popen self.process: subprocess.Popen
self.id: int self.id_iterator: Iterator[int]
self.id_lock: Lock
self.event_queues: Dict[int, Queue] self.event_queues: Dict[int, Queue]
# Map from request ID to `threading.Event`. # Map from request ID to `threading.Event`.
self.request_events: Dict[int, Event] self.request_events: Dict[int, Event]
@@ -55,8 +55,7 @@ class Rpc:
preexec_fn=os.setpgrp, # noqa: PLW1509 preexec_fn=os.setpgrp, # noqa: PLW1509
**self._kwargs, **self._kwargs,
) )
self.id = 0 self.id_iterator = itertools.count(start=1)
self.id_lock = Lock()
self.event_queues = {} self.event_queues = {}
self.request_events = {} self.request_events = {}
self.request_results = {} self.request_results = {}
@@ -145,11 +144,7 @@ class Rpc:
def __getattr__(self, attr: str): def __getattr__(self, attr: str):
def method(*args) -> Any: def method(*args) -> Any:
self.id_lock.acquire() request_id = next(self.id_iterator)
self.id += 1
request_id = self.id
self.id_lock.release()
request = { request = {
"jsonrpc": "2.0", "jsonrpc": "2.0",
"method": attr, "method": attr,