about summary refs log tree commit homepage
path: root/lib/dtas/unix_accepted.rb
blob: 6883ee14cb578d8aef3243757d11b185831a9186 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# -*- encoding: binary -*-
# :stopdoc:
# Copyright (C) 2013, Eric Wong <normalperson@yhbt.net>
# License: GPLv3 or later (https://www.gnu.org/licenses/gpl-3.0.txt)
require 'socket'
require 'io/wait'

class DTAS::UNIXAccepted
  attr_reader :to_io

  def initialize(sock)
    @to_io = sock
    @send_buf = []
  end

  # public API (for DTAS::Player)
  # returns :wait_readable on success
  def emit(msg)
    buffered = @send_buf.size
    if buffered == 0
      begin
        @to_io.sendmsg_nonblock(msg, Socket::MSG_EOR)
        return :wait_readable
      rescue Errno::EAGAIN
        @send_buf << msg
        return :wait_writable
      rescue => e
        return e
      end
    elsif buffered > 100
      return RuntimeError.new("too many messages buffered")
    else # buffered > 0
      @send_buf << msg
      return :wait_writable
    end
  end

  # flushes pending data if it got buffered
  def writable_iter
    begin
      msg = @send_buf.shift or return :wait_readable
      @to_io.send_nonblock(msg, Socket::MSG_EOR)
    rescue Errno::EAGAIN
      @send_buf.unshift(msg)
      return :wait_writable
    rescue => e
      return e
    end while true
  end

  def readable_iter
    io = @to_io
    nread = io.nread

    # EOF, assume no spurious wakeups for SOCK_SEQPACKET
    return nil if nread == 0

    begin
      begin
        msg, _, _ = io.recvmsg_nonblock(nread)
      rescue EOFError, SystemCallError
        return nil
      end
      yield(self, msg) # DTAS::Player deals with this
      nread = io.nread
    end while nread > 0
    :wait_readable
  end

  def close
    @to_io.close
  end

  def closed?
    @to_io.closed?
  end
end