Azoy / Sword

Discord library for Swift
https://azoy.github.io/Sword
MIT License
179 stars 52 forks source link

Please tell me about thread policy in this library #57

Open omochi opened 5 years ago

omochi commented 5 years ago

I have some questions about thread policy.

question 1

What is purpose of this code ?

https://github.com/Azoy/Sword/blob/19d7815cf499bb2b32055ef4cd74b7d0314b8ef5/Sources/Sword/Gateway/GatewayHandler.swift#L81-L89

ws.wait() blocks thread execution until this gateway connection close. So this code stops main thread. It blocks my application logic.

And if multiples Shard objects exists, first one blocks main thread. So same tasks from consequence other object will not run. If later shard close earlier than early shard, later shard task will not finish.

question 2

Simultaneous access from NIO thread and heartbeatQueue are safe ? I don't think so...

Shard.heartbeat method called in heartbeatQueue. It touches session, ackMissed. session property also touched from closure in GatewayHandler.conenct method. It should be from NIO thread. So these access may occur race condition.

Static object Sword.encoder also touched from these threads in Sword.send method.

question 3

What thread is intended to call GatewayHandler.connect and disconnect. These method looks public interface for user. Can user call them from main thread? disconnect method called from reconnect method. reconnect method called from heatbeat, handleClose, handlePayload. So disconnect called from NIO thread, heartbeatQueue, and main. I think it occurs race condition.