Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

connection_hub.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package hub
  2. import (
  3. "time"
  4. "go.uber.org/zap"
  5. "github.com/9seconds/mtg/protocol"
  6. )
  7. const hubGCEvery = time.Minute
  8. type connectionHubRequest struct {
  9. request *protocol.TelegramRequest
  10. response chan<- *connection
  11. }
  12. type connectionHub struct {
  13. sockets map[int]*connection
  14. logger *zap.SugaredLogger
  15. channelBrokenSockets chan int
  16. channelConnectionRequests chan *connectionHubRequest
  17. channelReturnConnections chan *connection
  18. }
  19. func (c *connectionHub) run() {
  20. ticker := time.NewTicker(hubGCEvery)
  21. defer ticker.Stop()
  22. for {
  23. select {
  24. case <-ticker.C:
  25. c.runGC()
  26. case request := <-c.channelConnectionRequests:
  27. c.runConnectionRequest(request)
  28. case id := <-c.channelBrokenSockets:
  29. c.runBrokenSocket(id)
  30. case conn := <-c.channelReturnConnections:
  31. c.runReturnConnection(conn)
  32. }
  33. }
  34. }
  35. func (c *connectionHub) runGC() {
  36. for key, conn := range c.sockets {
  37. switch {
  38. case conn.closed():
  39. delete(c.sockets, key)
  40. case conn.idle():
  41. conn.shutdown()
  42. delete(c.sockets, key)
  43. return
  44. }
  45. }
  46. }
  47. func (c *connectionHub) runConnectionRequest(req *connectionHubRequest) {
  48. for key, conn := range c.sockets {
  49. delete(c.sockets, key)
  50. if !conn.closed() {
  51. req.response <- conn
  52. close(req.response)
  53. return
  54. }
  55. }
  56. if conn, err := newConnection(req.request, c); err == nil {
  57. req.response <- conn
  58. }
  59. close(req.response)
  60. }
  61. func (c *connectionHub) runBrokenSocket(id int) {
  62. delete(c.sockets, id)
  63. }
  64. func (c *connectionHub) runReturnConnection(conn *connection) {
  65. c.sockets[conn.id] = conn
  66. }
  67. func newConnectionHub(logger *zap.SugaredLogger) *connectionHub {
  68. rv := &connectionHub{
  69. logger: logger.Named("connection-hub"),
  70. sockets: map[int]*connection{},
  71. channelBrokenSockets: make(chan int, 1),
  72. channelConnectionRequests: make(chan *connectionHubRequest),
  73. channelReturnConnections: make(chan *connection, 1),
  74. }
  75. go rv.run()
  76. return rv
  77. }