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.

ctx_channel.go 1.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. }