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
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ctx_channel.go 1.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package hub
  2. import (
  3. "context"
  4. "time"
  5. "github.com/9seconds/mtg/mtproto/rpc"
  6. )
  7. const closeableChannelReadTimeout = 2 * time.Minute
  8. type ChannelReadCloser interface {
  9. Read() (*rpc.ProxyResponse, error)
  10. Close() error
  11. }
  12. type ctxChannel struct {
  13. channel chan *rpc.ProxyResponse
  14. ctx context.Context
  15. cancel context.CancelFunc
  16. }
  17. func (c *ctxChannel) Read() (*rpc.ProxyResponse, error) {
  18. timer := time.NewTimer(closeableChannelReadTimeout)
  19. defer timer.Stop()
  20. select {
  21. case <-timer.C:
  22. return nil, ErrTimeout
  23. case <-c.ctx.Done():
  24. return nil, ErrClosed
  25. case packet := <-c.channel:
  26. return packet, nil
  27. }
  28. }
  29. func (c *ctxChannel) sendBack(response *rpc.ProxyResponse) error {
  30. select {
  31. case <-c.ctx.Done():
  32. return ErrClosed
  33. case c.channel <- response:
  34. return nil
  35. }
  36. }
  37. func (c *ctxChannel) Close() error {
  38. c.cancel()
  39. c.channel = nil
  40. return nil
  41. }
  42. func newCtxChannel(ctx context.Context) *ctxChannel {
  43. ctx, cancel := context.WithCancel(ctx)
  44. return &ctxChannel{
  45. channel: make(chan *rpc.ProxyResponse),
  46. ctx: ctx,
  47. cancel: cancel,
  48. }
  49. }