Sha256: 6cfba777cefff852beaec1e39a54ebe5075838676d4dafbb3ce8c91bbee23df7

Contents?: true

Size: 1.67 KB

Versions: 5

Compression:

Stored size: 1.67 KB

Contents

# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2020-2022, by Samuel Williams.
# Copyright, 2020, by Olle Jonsson.

require 'async/io'
require 'async/io/unix_endpoint'
require 'kernel/sync'

require 'tmpdir'
require 'securerandom'

module Async
	module Container
		module Notify
			class Server
				NOTIFY_SOCKET = 'NOTIFY_SOCKET'
				MAXIMUM_MESSAGE_SIZE = 4096
				
				def self.load(message)
					lines = message.split("\n")
					
					lines.pop if lines.last == ""
					
					pairs = lines.map do |line|
						key, value = line.split("=", 2)
						
						if value == '0'
							value = false
						elsif value == '1'
							value = true
						end
						
						next [key.downcase.to_sym, value]
					end
					
					return Hash[pairs]
				end
				
				def self.generate_path
					File.expand_path(
						"async-container-#{::Process.pid}-#{SecureRandom.hex(8)}.ipc",
						Dir.tmpdir
					)
				end
				
				def self.open(path = self.generate_path)
					self.new(path)
				end
				
				def initialize(path)
					@path = path
				end
				
				attr :path
				
				def bind
					Context.new(@path)
				end
				
				class Context
					def initialize(path)
						@path = path
						@endpoint = IO::Endpoint.unix(@path, ::Socket::SOCK_DGRAM)
						
						Sync do
							@bound = @endpoint.bind
						end
						
						@state = {}
					end
					
					def close
						Sync do
							@bound.close
						end
						
						File.unlink(@path)
					end
					
					def receive
						while true
							data, _address, _flags, *_controls = @bound.recvmsg(MAXIMUM_MESSAGE_SIZE)
							
							message = Server.load(data)
							
							yield message
						end
					end
				end
			end
		end
	end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
async-container-0.18.1 lib/async/container/notify/server.rb
async-container-0.18.0 lib/async/container/notify/server.rb
async-container-0.17.1 lib/async/container/notify/server.rb
async-container-0.17.0 lib/async/container/notify/server.rb
async-container-0.16.13 lib/async/container/notify/server.rb