domingo, 23 de febrero de 2025

TDLib & Process synchronization

Telegram works based on asynchronous RPC calls, so interacting with the API implies sending the payload that represents the call to the function and receiving a result. This mode of operation avoids blockages, but implies the need to correctly manage communication between processes.

 To implement a correct operation on my Bachelor's Degree Final Project,it was necessary to divide the API call management logic into two different actions. On the one hand, the result of the call is handled in class Telegram.java, and on the other hand, a spinlock is used to synchronize communication between processes.


HANDLE THE ANSWER:

To handle client-server interactions, the Telegram.java class adds a DefaultHandler object to each API call. The onResult(TdApi.Object object) method then receives the response when it is available.

The original functionality of the onResult() method was limited to printing the result of the call, a TL (Type Language) object such as the following, through the standard output of the system.




This functionality did not meet the requirements of the project since it was desired to natively retrieve the types of objects handled by Telegram: FoundMessages, Chats, User, etc.

To obtain the desired functionality, a feature of the TDLib design was taken advantage of.  Each type of object has a unique identifier defined in its constructor. For example, in the following figure it can be seen that the identifier -448050478 corresponds to an object type 'photo message'





The implemented solution modifies the onResult() method by adding a switch-case structure where the value of the constructor of the received object is used as a parameter in the switch and then the response is handled according to the corresponding needs. Here's an example.



After the response is captured and the received object is handled successfully, the value of the control variable is set to true to inform the calling method that it can end the spinlock. If there is a problem with the call, the default case is executed and the active wait is terminated.

Once the spinlock is finished, the corresponding object is retrieved and the lock variable is rearmed for the next request. If the result of the call is not as expected, the situation is handled appropriately.





Enjoy, 

Culex