licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 534 | ### protocol.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <[email protected]>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file aggregates all utilities needed for handling NATS protocol.
#
### Code:
include("structs.jl")
include("errors.jl")
include("validate.jl")
include("parser.jl")
include("payload.jl")
include("headers.jl")
include("convert.jl")
include("show.jl")
include("crc16.jl")
include("nkeys.jl")
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 4208 | ### show.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <[email protected]>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains serialization utilities for converting structures into NATS protocol payload.
#
### Code:
import StructTypes: omitempties
# Payload serialization.
function Base.show(io::IO, ::MIME_PAYLOAD, ::Nothing)
# Empty payload, nothing to write.
nothing
end
function Base.show(io::IO, ::MIME_PAYLOAD, ::Headers)
# When only headers are provided, do not write any payload.
# TODO: what if someone used Vector{Pair{String, String}} as payload?
nothing
end
function Base.show(io::IO, ::MIME_PAYLOAD, payload::String)
# Allows to return string from handler for `reply`.
write(io, payload)
nothing
end
function Base.show(io::IO, ::MIME_PAYLOAD, payload::JSON3.Object)
# Allows to return json from handler for `reply`.
JSON3.write(io, payload)
nothing
end
function Base.show(io::IO, mime::MIME_PAYLOAD, tup::Tuple{<:Any, Headers})
# Allows to return tuple from handler, useful to override headers.
Base.show(io, mime, first(tup))
nothing
end
function Base.show(io::IO, mime::MIME_PAYLOAD, tup::Tuple{<:Any, Nothing})
# Handle edge case when some method will return nothing headers, but still in a tuple with payload.
Base.show(io, mime, first(tup))
nothing
end
# Headers serialization.
function Base.show(io::IO, ::MIME_HEADERS, ::Any)
# Default is empty header.
nothing
end
function Base.show(io::IO, ::MIME_HEADERS, ::Nothing)
# Empty headers, nothing to write.
nothing
end
function Base.show(io::IO, mime::MIME_HEADERS, tup::Tuple{<:Any, Headers})
Base.show(io, mime, last(tup))
nothing
end
function Base.show(io::IO, mime::MIME_HEADERS, s::String)
startswith(s, "NATS/1.0\r\n") && write(io, s) # TODO: better validations, not sure if this method is needed.
nothing
end
function Base.show(io::IO, ::MIME_HEADERS, headers::Headers)
print(io, "NATS/1.0\r\n")
for (key, value) in headers
print(io, key)
print(io, ": ")
print(io, value)
print(io, "\r\n")
end
print(io, "\r\n")
nothing
end
# Protocol serialization.
StructTypes.omitempties(::Type{Connect}) = true
function show(io::IO, ::MIME_PROTOCOL, connect::Connect)
write(io, "CONNECT $(JSON3.write(connect))\r\n")
end
function show(io::IO, ::MIME_PROTOCOL, pub::Pub)
hbytes = pub.headers_length
nbytes = length(pub.payload)
if hbytes > 0
write(io, "H")
end
write(io, "PUB ")
write(io, pub.subject)
if !isnothing(pub.reply_to) && !isempty(pub.reply_to)
write(io, " ")
write(io, pub.reply_to)
end
if hbytes > 0
write(io, " $hbytes")
end
write(io, ' ')
show(io, nbytes)
# write(io, string(nbytes))
write(io, "\r\n")
write(io, pub.payload)
write(io, "\r\n")
end
function show(io::IO, ::MIME_PROTOCOL, sub::Sub)
queue_group = isnothing(sub.queue_group) ? "" : " $(sub.queue_group)"
write(io, "SUB $(sub.subject)$queue_group $(sub.sid)\r\n")
end
function show(io::IO, ::MIME_PROTOCOL, unsub::Unsub)
max_msgs = isnothing(unsub.max_msgs) ? "" : " $(unsub.max_msgs)"
write(io, "UNSUB $(unsub.sid)$max_msgs\r\n")
end
function show(io::IO, ::MIME_PROTOCOL, unsub::Ping)
write(io, "PING\r\n")
end
function show(io::IO, ::MIME_PROTOCOL, unsub::Pong)
write(io, "PONG\r\n")
end
# Pretty print Msg.
function show(io::IO, mime::MIME"text/plain", msg::Msg)
payload_limit = 500
if msg.headers_length > 0
write(io, "H")
end
write(io, "MSG $(msg.subject) $(msg.sid) ")
if !(isnothing(msg.reply_to))
write(io, "$(msg.reply_to) ")
end
if msg.headers_length > 0
write(io, "$(msg.headers_length) ")
end
write(io, "$(length(msg.payload))\r\n")
if length(msg.payload) > payload_limit
write(io, String(first(msg.payload, payload_limit)))
write(io, " ⋯ $(length(msg.payload) - payload_limit) bytes")
else
write(io, String(copy(msg.payload)))
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 9910 | ### structs.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <[email protected]>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains data structures describing NATS protocol.
#
### Code:
abstract type ProtocolMessage end
"""
A client will need to start as a plain TCP connection, then when the server accepts a connection from the client, it will send information about itself, the configuration and security requirements necessary for the client to successfully authenticate with the server and exchange messages. When using the updated client protocol (see CONNECT below), INFO messages can be sent anytime by the server. This means clients with that protocol level need to be able to asynchronously handle INFO messages.
$(TYPEDFIELDS)
"""
struct Info <: ProtocolMessage
"The unique identifier of the NATS server."
server_id::String
"The name of the NATS server."
server_name::String
"The version of NATS."
version::String
"The version of golang the NATS server was built with."
go::String
"The IP address used to start the NATS server, by default this will be `0.0.0.0` and can be configured with `-client_advertise host:port`."
host::String
"The port number the NATS server is configured to listen on."
port::Int
"Whether the server supports headers."
headers::Bool
"Maximum payload size, in bytes, that the server will accept from the client."
max_payload::Int
"An integer indicating the protocol version of the server. The server version 1.2.0 sets this to `1` to indicate that it supports the \"Echo\" feature."
proto::Int
"The internal client identifier in the server. This can be used to filter client connections in monitoring, correlate with error logs, etc..."
client_id::Union{UInt64, Nothing}
"If this is true, then the client should try to authenticate upon connect."
auth_required::Union{Bool, Nothing}
"If this is true, then the client must perform the TLS/1.2 handshake. Note, this used to be `ssl_required` and has been updated along with the protocol from SSL to TLS."
tls_required::Union{Bool, Nothing}
"If this is true, the client must provide a valid certificate during the TLS handshake."
tls_verify::Union{Bool, Nothing}
"If this is true, the client can provide a valid certificate during the TLS handshake."
tls_available::Union{Bool, Nothing}
"List of server urls that a client can connect to."
connect_urls::Union{Vector{String}, Nothing}
"List of server urls that a websocket client can connect to."
ws_connect_urls::Union{Vector{String}, Nothing}
"If the server supports *Lame Duck Mode* notifications, and the current server has transitioned to lame duck, `ldm` will be set to `true`."
ldm::Union{Bool, Nothing}
"The git hash at which the NATS server was built."
git_commit::Union{String, Nothing}
"Whether the server supports JetStream."
jetstream::Union{Bool, Nothing}
"The IP of the server."
ip::Union{String, Nothing}
"The IP of the client."
client_ip::Union{String, Nothing}
"The nonce for use in CONNECT."
nonce::Union{String, Nothing}
"The name of the cluster."
cluster::Union{String, Nothing}
"The configured NATS domain of the server."
domain::Union{String, Nothing}
end
"""
The CONNECT message is the client version of the `INFO` message. Once the client has established a TCP/IP socket connection with the NATS server, and an `INFO` message has been received from the server, the client may send a `CONNECT` message to the NATS server to provide more information about the current connection as well as security information.
$(TYPEDFIELDS)
"""
struct Connect <: ProtocolMessage
# TODO: restore link #NATS.Ok
"Turns on `+OK` protocol acknowledgements."
verbose::Bool
"Turns on additional strict format checking, e.g. for properly formed subjects."
pedantic::Bool
"Indicates whether the client requires SSL connection."
tls_required::Bool
"Client authorization token."
auth_token::Union{String, Nothing}
"Connection username."
user::Union{String, Nothing}
"Connection password."
pass::Union{String, Nothing}
"Client name."
name::Union{String, Nothing}
"The implementation language of the client."
lang::String
"The version of the client."
version::String
# TODO: restore link ./#NATS.Info
"Sending `0` (or absent) indicates client supports original protocol. Sending `1` indicates that the client supports dynamic reconfiguration of cluster topology changes by asynchronously receiving `INFO` messages with known servers it can reconnect to."
protocol::Union{Int, Nothing}
"If set to `false`, the server (version 1.2.0+) will not send originating messages from this connection to its own subscriptions. Clients should set this to `false` only for server supporting this feature, which is when `proto` in the `INFO` protocol is set to at least `1`."
echo::Union{Bool, Nothing}
"In case the server has responded with a `nonce` on `INFO`, then a NATS client must use this field to reply with the signed `nonce`."
sig::Union{String, Nothing}
"The JWT that identifies a user permissions and account."
jwt::Union{String, Nothing}
"Enable quick replies for cases where a request is sent to a topic with no responders."
no_responders::Union{Bool, Nothing}
"Whether the client supports headers."
headers::Union{Bool, Nothing}
"The public NKey to authenticate the client. This will be used to verify the signature (`sig`) against the `nonce` provided in the `INFO` message."
nkey::Union{String, Nothing}
end
"""
The PUB message publishes the message payload to the given subject name, optionally supplying a reply subject. If a reply subject is supplied, it will be delivered to eligible subscribers along with the supplied payload. Note that the payload itself is optional. To omit the payload, set the payload size to 0, but the second CRLF is still required.
The HPUB message is the same as PUB but extends the message payload to include NATS headers. Note that the payload itself is optional. To omit the payload, set the total message size equal to the size of the headers. Note that the trailing CR+LF is still required.
$(TYPEDFIELDS)
"""
struct Pub <: ProtocolMessage
"The destination subject to publish to."
subject::String
"The reply subject that subscribers can use to send a response back to the publisher/requestor."
reply_to::Union{String, Nothing}
"Length of headers data inside payload"
headers_length::Int64
"Optional headers (`NATS/1.0␍␊` followed by one or more `name: value` pairs, each separated by `␍␊`) followed by payload data."
payload::Vector{UInt8}
end
"""
`SUB` initiates a subscription to a subject, optionally joining a distributed queue group.
$(TYPEDFIELDS)
"""
struct Sub <: ProtocolMessage
"The subject name to subscribe to."
subject::String
"If specified, the subscriber will join this queue group."
queue_group::Union{String, Nothing}
"A unique alphanumeric subscription ID, generated by the client."
sid::Int64
end
"""
`UNSUB` unsubscribes the connection from the specified subject, or auto-unsubscribes after the specified number of messages has been received.
$(TYPEDFIELDS)
"""
struct Unsub <: ProtocolMessage
"The unique alphanumeric subscription ID of the subject to unsubscribe from."
sid::Int64
"A number of messages to wait for before automatically unsubscribing."
max_msgs::Union{Int, Nothing}
end
# Representation of MSG returned by parser, it will be converted to `Msg` struct in subscription handler task.
struct MsgRaw <: ProtocolMessage
sid::Int64
buffer::Vector{UInt8}
subject_range::UnitRange{Int64}
reply_to_range::UnitRange{Int64}
header_bytes::Int64
payload_range::UnitRange{Int64}
end
"""
The `MSG` protocol message is used to deliver an application message to the client.
The HMSG message is the same as MSG, but extends the message payload with headers. See also [ADR-4 NATS Message Headers](https://github.com/nats-io/nats-architecture-and-design/blob/main/adr/ADR-4.md).
$(TYPEDFIELDS)
"""
struct Msg <: ProtocolMessage
"Subject name this message was received on."
subject::String
"The unique alphanumeric subscription ID of the subject."
sid::Int64
"The subject on which the publisher is listening for responses."
reply_to::Union{String, Nothing}
"Length of headers data inside payload"
headers_length::Int64
"Optional headers (`NATS/1.0␍␊` followed by one or more `name: value` pairs, each separated by `␍␊`) followed by payload data."
payload::AbstractVector{UInt8}
end
"""
`PING` and `PONG` implement a simple keep-alive mechanism between client and server.
$(TYPEDFIELDS)
"""
struct Ping <: ProtocolMessage
end
"""
`PING` and `PONG` implement a simple keep-alive mechanism between client and server.
$(TYPEDFIELDS)
"""
struct Pong <: ProtocolMessage
end
"""
The `-ERR` message is used by the server indicate a protocol, authorization, or other runtime connection error to the client. Most of these errors result in the server closing the connection.
$(TYPEDFIELDS)
"""
struct Err <: ProtocolMessage
"Error message."
message::String
end
"""
When the `verbose` connection option is set to `true` (the default value), the server acknowledges each well-formed protocol message from the client with a `+OK` message.
$(TYPEDFIELDS)
"""
struct Ok <: ProtocolMessage
end
# This allows structural equality on protocol messages with `==` and `isequal` functions.
function Base.:(==)(a::M, b::M) where {M <: ProtocolMessage}
all(field -> getfield(a, field) == getfield(b, field), fieldnames(M))
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 786 | ### validate.jl
#
# Copyright (C) 2024 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <[email protected]>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementation of functions for validation of protocol messages.
#
### Code:
function validate(pub::Pub)
isempty(pub.subject) && error("Publication subject is empty")
startswith(pub.subject, '.') && error("Publication subject '$(pub.subject)' cannot start with '.'")
endswith(pub.subject, '.') && error("Publication subject '$(pub.subject)' cannot end with '.'")
for c in pub.subject
if c == ' '
error("Publication subject contains invalid character '$c'.")
end
end
true
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1773 | ### drain.jl
#
# Copyright (C) 2024 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <[email protected]>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementation of subscrption draining what means to
# unsubscribe and ensure all pending messages in buffers are processed.
#
### Code:
"""
$SIGNATURES
Unsubscribe a subscription and wait for precessing all messages in the buffer.
Underneeth it periodicaly checks for state of the buffer, interval for checks
is configurable per connection with `drain_poll` parameter of `connect` method.
It can also be set globally with `NATS_DRAIN_POLL_INTERVAL_SECONDS` environment
variable. If not set explicitly default polling interval is
`$DEFAULT_DRAIN_POLL_INTERVAL_SECONDS` seconds.
Optional keyword arguments:
- `timer`: error will be thrown if drain not finished until `timer` expires. Default value is configurable per connection on `connect` with `drain_timeout`. Can be also set globally with `NATS_DRAIN_TIMEOUT_SECONDS` environment variable. If not set explicitly default drain timeout is `$DEFAULT_DRAIN_TIMEOUT_SECONDS` seconds.
"""
function drain(connection::Connection, sub::Sub; timer::Timer = Timer(connection.drain_timeout))
sub_stats = stats(connection, sub)
if isnothing(sub_stats)
return # Already drained.
end
send(connection, Unsub(sub.sid, 0))
sleep(connection.drain_poll)
while !is_every_message_handled(sub_stats)
if !isopen(timer)
@error "Timeout for drain exceeded, not all msgs might be processed." sub
break
end
sleep(connection.drain_poll)
end
cleanup_sub_resources(connection, sub.sid)
nothing
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1640 | ### publish.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <[email protected]>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementation of functions for publishing messages.
#
### Code:
const mime_payload = MIME_PAYLOAD()
const mime_headers = MIME_HEADERS()
"""
$(SIGNATURES)
Publish `data` to a `subject`, payload is obtained with `show` method taking `mime` `$(MIME_PAYLOAD())`, headers are obtained with `show` method taking `mime` `$(MIME_HEADERS())`.
There are predefined convertion defined for `String` type. To publish headers there is defined conversion from tuple taking vector of pairs of strings.
Optional parameters:
- `reply_to`: subject to which a result should be published
Examples:
```
publish(nc, "some_subject", "Some payload")
publish("some_subject", ("Some payload", ["some_header" => "Example header value"]))
```
"""
function publish(
connection::Connection,
subject::String,
data = nothing;
reply_to::Union{String, Nothing} = nothing
)
payload_io = IOBuffer()
show(payload_io, mime_headers, data)
headers_length = payload_io.size
show(payload_io, mime_payload, data)
payload_bytes = take!(payload_io)
pub = Pub(subject, reply_to, headers_length, payload_bytes)
validate(pub)
send(connection, pub)
inc_stats(:msgs_published, 1, connection.stats, state.stats)
sub_stats = ScopedValues.get(scoped_subscription_stats)
if !isnothing(sub_stats)
inc_stat(sub_stats.value, :msgs_published, 1)
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 411 | ### pubsub.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <[email protected]>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains aggregates utils for publish - subscribe pattern.
#
### Code:
include("publish.jl")
include("subscribe.jl")
include("unsubscribe.jl")
include("drain.jl")
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 12858 | ### subscribe.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <[email protected]>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementation of functions for subscribing to subjects.
#
### Code:
"""
$(SIGNATURES)
Subscribe to a subject.
Optional keyword arguments are:
- `queue_group`: NATS server will distribute messages across queue group members
- `spawn`: if `true` task will be spawn for each `f` invocation, otherwise messages are processed sequentially, default is `false`
- `channel_size`: maximum items buffered for processing, if full messages will be ignored, default is `$DEFAULT_SUBSCRIPTION_CHANNEL_SIZE`, can be configured globally with `NATS_SUBSCRIPTION_CHANNEL_SIZE` env variable
- `monitoring_throttle_seconds`: time intervals in seconds that handler errors will be reported in logs, default is `$DEFAULT_SUBSCRIPTION_ERROR_THROTTLING_SECONDS` seconds, can be configured globally with `NATS_SUBSCRIPTION_ERROR_THROTTLING_SECONDS` env variable
"""
function subscribe(
f,
connection::Connection,
subject::String;
queue_group::Union{String, Nothing} = nothing,
spawn::Bool = false,
channel_size::Int64 = parse(Int64, get(ENV, "NATS_SUBSCRIPTION_CHANNEL_SIZE", string(DEFAULT_SUBSCRIPTION_CHANNEL_SIZE))),
monitoring_throttle_seconds::Float64 = parse(Float64, get(ENV, "NATS_SUBSCRIPTION_ERROR_THROTTLING_SECONDS", string(DEFAULT_SUBSCRIPTION_ERROR_THROTTLING_SECONDS)))
)
f_typed = _fast_call(f)
sid = new_sid(connection)
sub = Sub(subject, queue_group, sid)
sub_stats = Stats()
subscription_channel = Channel(channel_size)
with(scoped_subscription_stats => sub_stats) do
_start_tasks(f_typed, sub_stats, connection.stats, spawn, subject, subscription_channel, monitoring_throttle_seconds)
end
@lock connection.lock begin
connection.sub_data[sid] = SubscriptionData(sub, subscription_channel, sub_stats, true, ReentrantLock())
end
send(connection, sub)
sub
end
"""
$(SIGNATURES)
Subscribe to a subject in synchronous mode. Client is supposed to call `next` manually to obtain messages.
Optional keyword arguments are:
- `queue_group`: NATS server will distribute messages across queue group members
- `channel_size`: maximum items buffered for processing, if full messages will be ignored, default is `$DEFAULT_SUBSCRIPTION_CHANNEL_SIZE`, can be configured globally with `NATS_SUBSCRIPTION_CHANNEL_SIZE` env variable
- `monitoring_throttle_seconds`: time intervals in seconds that handler errors will be reported in logs, default is `$DEFAULT_SUBSCRIPTION_ERROR_THROTTLING_SECONDS` seconds, can be configured globally with `NATS_SUBSCRIPTION_ERROR_THROTTLING_SECONDS` env variable
"""
function subscribe(
connection::Connection,
subject::String;
queue_group::Union{String, Nothing} = nothing,
channel_size::Int64 = parse(Int64, get(ENV, "NATS_SUBSCRIPTION_CHANNEL_SIZE", string(DEFAULT_SUBSCRIPTION_CHANNEL_SIZE))),
monitoring_throttle_seconds::Float64 = parse(Float64, get(ENV, "NATS_SUBSCRIPTION_ERROR_THROTTLING_SECONDS", string(DEFAULT_SUBSCRIPTION_ERROR_THROTTLING_SECONDS)))
)
sid = new_sid(connection)
sub = Sub(subject, queue_group, sid)
sub_stats = Stats()
subscription_channel = Channel(channel_size)
@lock connection.lock begin
connection.sub_data[sid] = SubscriptionData(sub, subscription_channel, sub_stats, false, ReentrantLock())
end
send(connection, sub)
subscription_monitoring_task = Threads.@spawn :interactive disable_sigint() do
while isopen(subscription_channel) || Base.n_avail(subscription_channel) > 0
sleep(monitoring_throttle_seconds)
# Warn if subscription channel is too small.
level = Base.n_avail(subscription_channel) / subscription_channel.sz_max
if level > 0.8 # TODO: add to config.
stats = NATS.stats(connection, sub)
@warn "Subscription on $subject channel is full in $(100 * level) %, dropped messages: $(stats.msgs_dropped)"
end
end
# @debug "Subscription monitoring task finished" subject
end
errormonitor(subscription_monitoring_task)
sub
end
"""
$(SIGNATURES)
Obtains next message for synchronous subscription.
Optional keyword arguments:
- `no_wait`: do not wait for next message, return `nothing` if buffer is empty
- `no_throw`: do not throw exception, returns `nothing` if cannot get next message
"""
function next(connection::Connection, sub::Sub; no_wait = false, no_throw = false)::Union{Msg, Nothing}
sub_data = @lock connection.lock get(connection.sub_data, sub.sid, nothing)
if isnothing(sub_data)
no_throw && return nothing
throw(NATSError(499, "Client unsubscribed."))
end
sub_data.is_async && error("`next` is available only for synchronous subscriptions")
ch = sub_data.channel
if no_wait && Base.n_avail(ch) == 0 # Double check emptiness for thread safety.
if !isopen(ch) && Base.n_avail(ch) == 0
@lock connection.lock begin
delete!(connection.sub_data, sub.sid)
delete!(connection.unsubs, sub.sid)
end
end
return nothing
end
msg =
try
@lock sub_data.lock begin
batch = fetch(ch)
result = popfirst!(batch)
isempty(batch) && take!(ch)
result
end
catch err
err isa InterruptException && rethrow()
no_throw && return nothing
if err isa InvalidStateException
throw(NATSError(499, "Client unsubscribed."))
end
rethrow()
finally
if !isopen(ch) && Base.n_avail(ch) == 0
@lock connection.lock begin
delete!(connection.sub_data, sub.sid)
delete!(connection.unsubs, sub.sid)
end
end
end
dec_stats(:msgs_pending, 1, sub_data.stats, connection.stats, state.stats)
inc_stats(:msgs_handled, 1, sub_data.stats, connection.stats, state.stats)
msg = convert(Msg, msg)
no_throw || throw_on_error_status(msg)
msg
end
"""
$(SIGNATURES)
Obtains next message for synchronous subscription converting it to requested `T` type.
Optional keyword arguments:
- `no_wait`: do not wait for next message, return `nothing` if buffer is empty
- `no_throw`: do not throw exception, returns `nothing` if cannot get next message
"""
function next(T::Type, connection::Connection, sub::Sub; no_wait = false, no_throw = false)::Union{T, Nothing}
find_msg_conversion_or_throw(T)
msg = next(connection, sub; no_wait, no_throw)
isnothing(msg) ? nothing : convert(T, msg) #TODO: invokelatest
end
"""
$(SIGNATURES)
Obtains batch of messages for synchronous subscription.
Optional keyword arguments:
- `no_wait`: do not wait for next message, return empty vector if buffer is empty
- `no_throw`: do not throw exception, stops collecting messages on error
"""
function next(connection::Connection, sub::Sub, batch::Integer; no_wait = false, no_throw = false)::Vector{Msg}
msgs = []
for i in 1:batch
msg = next(connection, sub; no_wait, no_throw)
isnothing(msg) && break
push!(msgs, msg)
end
msgs
end
"""
$(SIGNATURES)
Obtains batch of messages for synchronous subscription converting them to reqested `T` type.
Optional keyword arguments:
- `no_wait`: do not wait for next message, return empty vector if buffer is empty
- `no_throw`: do not throw exception, stops collecting messages on error
"""
function next(T::Type, connection::Connection, sub::Sub, batch::Integer; no_wait = false, no_throw = false)::Vector{T}
find_msg_conversion_or_throw(T)
convert.(T, next(connection, sub, batch; no_wait, no_throw)) #TODO: invokelatest
end
@kwdef mutable struct SubscriptionMonitoringData
last_error::Union{Any, Nothing} = nothing
last_error_msg::Union{Msg, Nothing} = nothing
errors_since_last_report::Int64 = 0
lock::ReentrantLock = Threads.ReentrantLock()
end
function report_error!(data::SubscriptionMonitoringData, err, msg::Msg)
@lock data.lock begin
data.last_error = err
data.last_error_msg = msg
data.errors_since_last_report += 1
end
end
# Resets errors counter and obtains current state.
function reset_counter!(data::SubscriptionMonitoringData)
@lock data.lock begin
save = data.errors_since_last_report
data.errors_since_last_report = 0
save, data.last_error, data.last_error_msg
end
end
function _start_tasks(f::Function, sub_stats::Stats, conn_stats::Stats, spawn::Bool, subject::String, subscription_channel::Channel, monitoring_throttle_seconds::Float64)
monitoring_data = SubscriptionMonitoringData()
if spawn == true
subscription_task = Threads.@spawn :interactive disable_sigint() do
try
while true
msgs = take!(subscription_channel)
for msg in msgs
handler_task = Threads.@spawn :default disable_sigint() do
msg = convert(Msg, msg)
try
dec_stats(:msgs_pending, 1, sub_stats, conn_stats, state.stats)
inc_stats(:handlers_running, 1, sub_stats, conn_stats, state.stats)
f(msg)
inc_stats(:msgs_handled, 1, sub_stats, conn_stats, state.stats)
dec_stats(:handlers_running, 1, sub_stats, conn_stats, state.stats)
catch err
inc_stats(:msgs_errored, 1, sub_stats, conn_stats, state.stats)
dec_stats(:handlers_running, 1, sub_stats, conn_stats, state.stats)
report_error!(monitoring_data, err, msg)
end
end
# errormonitor(handler_task) # TODO: enable this on debug.
end
end
catch err
err isa InvalidStateException || rethrow()
end
end
errormonitor(subscription_task)
else
subscription_task = Threads.@spawn :default disable_sigint() do
try
while true
msgs = take!(subscription_channel)
for msg in msgs
msg = convert(Msg, msg)
try
dec_stats(:msgs_pending, 1, sub_stats, conn_stats, state.stats)
inc_stats(:handlers_running, 1, sub_stats, conn_stats, state.stats)
f(msg)
inc_stats(:msgs_handled, 1, sub_stats, conn_stats, state.stats)
dec_stats(:handlers_running, 1, sub_stats, conn_stats, state.stats)
catch err
inc_stats(:msgs_errored, 1, sub_stats, conn_stats, state.stats)
dec_stats(:handlers_running, 1, sub_stats, conn_stats, state.stats)
report_error!(monitoring_data, err, msg)
end
end
end
catch err
err isa InvalidStateException || rethrow()
end
end
errormonitor(subscription_task)
end
subscription_monitoring_task = Threads.@spawn :interactive disable_sigint() do
while isopen(subscription_channel) || Base.n_avail(subscription_channel) > 0
sleep(monitoring_throttle_seconds)
# Warn about too many handlers running.
handlers_running = sub_stats.handlers_running
if handlers_running > 1000 # TODO: add to config.
@warn "$(handlers_running) handlers running for subscription on $subject."
end
# Warn if subscription channel is too small.
level = Base.n_avail(subscription_channel) / subscription_channel.sz_max
if level > 0.8 # TODO: add to config.
@warn "Subscription on $subject channel full in $(100 * level) %"
end
# Report errors thrown by the handler function.
errs, err, msg = reset_counter!(monitoring_data)
if errs > 0
@error "$errs handler errors on \"$subject\" in last $monitoring_throttle_seconds s." err msg
end
end
# @debug "Subscription monitoring task finished" subject
end
errormonitor(subscription_monitoring_task)
nothing
end | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1177 | ### unsubscribe.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <[email protected]>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementation of functions for unsubscribing a subscription.
#
### Code:
"""
$(SIGNATURES)
Unsubscrible from a subject. `sub` is an object returned from `subscribe` or `reply`.
Optional keyword arguments are:
- `max_msgs`: maximum number of messages server will send after `unsubscribe` message received in server side, what can occur after some time lag
"""
function unsubscribe(
connection::Connection,
sub::Sub;
max_msgs::Union{Int, Nothing} = nothing
)
unsubscribe(connection, sub.sid; max_msgs)
end
function unsubscribe(
connection::Connection,
sid::Int64;
max_msgs::Union{Int, Nothing} = nothing
)
usnub = Unsub(sid, max_msgs)
send(connection, usnub)
if isnothing(max_msgs) || max_msgs == 0
cleanup_sub_resources(connection, sid)
else
@lock connection.lock begin
connection.unsubs[sid] = max_msgs
end
end
nothing
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1389 | ### reply.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <[email protected]>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementations of functions for replying to a subject.
#
### Code:
"""
$(SIGNATURES)
Reply for messages for a `subject`. Works like `subscribe` with automatic `publish` to the subject from `reply_to` field.
Optional keyword arguments are:
- `queue_group`: NATS server will distribute messages across queue group members
- `spawn`: if `true` task will be spawn for each `f` invocation, otherwise messages are processed sequentially, default is `false`
# Examples
```julia-repl
julia> sub = reply("FOO.REQUESTS") do msg
"This is a reply payload."
end
NATS.Sub("FOO.REQUESTS", nothing, "jdnMEcJN")
julia> sub = reply("FOO.REQUESTS") do msg
"This is a reply payload.", ["example_header" => "This is a header value"]
end
NATS.Sub("FOO.REQUESTS", nothing, "jdnMEcJN")
julia> unsubscribe(sub)
```
"""
function reply(
f,
connection::Connection,
subject::String;
queue_group::Union{Nothing, String} = nothing,
spawn::Bool = false
)
fast_f = _fast_call(f)
subscribe(connection, subject; queue_group, spawn) do msg
data = fast_f(msg)
publish(connection, msg.reply_to, data)
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 359 | ### reqreply.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <[email protected]>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains aggregates utils for request - reply pattern.
#
### Code:
include("request.jl")
include("reply.jl")
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 3667 | ### request.jl
#
# Copyright (C) 2023 Jakub Wronowski.
#
# Maintainer: Jakub Wronowski <[email protected]>
# Keywords: nats, nats-client, julia
#
# This file is a part of NATS.jl.
#
# License is MIT.
#
### Commentary:
#
# This file contains implementations of functions for requesting a reply.
#
### Code:
"""
$(SIGNATURES)
Send NATS [Request-Reply](https://docs.nats.io/nats-concepts/core-nats/reqreply) message.
Default timeout is $DEFAULT_REQUEST_TIMEOUT_SECONDS seconds which can be overriden by passing `timer`. It can be configured globally with `NATS_REQUEST_TIMEOUT_SECONDS` env variable.
Optional keyword arguments are:
- `timer`: error will be thrown if no replies received until `timer` expires
# Examples
```julia-repl
julia> NATS.request(connection, "help.please")
NATS.Msg("l9dKWs86", "7Nsv5SZs", nothing, "", "OK, I CAN HELP!!!")
julia> request(connection, "help.please"; timer = Timer(0))
ERROR: No replies received.
```
"""
function request(
connection::Connection,
subject::String,
data = nothing;
timer::Timer = Timer(parse(Float64, get(ENV, "NATS_REQUEST_TIMEOUT_SECONDS", string(DEFAULT_REQUEST_TIMEOUT_SECONDS))))
)
replies = request(connection, 1, subject, data; timer)
if isempty(replies)
throw(NATSError(408, "No replies received in specified time."))
end
if length(replies) > 1
@warn "Multiple replies."
end
msg = first(replies)
throw_on_error_status(msg)
msg
end
"""
$(SIGNATURES)
Requests for multiple replies. Vector of messages is returned after receiving `nreplies` replies or timer expired.
Can return less messages than specified (also empty array if timeout occurs), errors are not filtered.
Optional keyword arguments are:
- `timer`: empty vector will be returned if no replies received until `timer` expires
# Examples
```julia-repl
julia> request(connection, 2, "help.please"; timer = Timer(0))
NATS.Msg[]
```
"""
function request(
connection::Connection,
nreplies::Integer,
subject::String,
data = nothing;
timer::Timer = Timer(parse(Float64, get(ENV, "NATS_REQUEST_TIMEOUT_SECONDS", string(DEFAULT_REQUEST_TIMEOUT_SECONDS))))
)
find_data_conversion_or_throw(typeof(data))
if NATS.status(connection) in [NATS.DRAINED, NATS.DRAINING]
throw(NATS.NATSError(499, "Connection is drained."))
end
nreplies < 1 && error("`nreplies` have to be greater than 0.")
reply_to = new_inbox(connection)
sub = subscribe(connection, reply_to)
unsubscribe(connection, sub; max_msgs = nreplies)
publish(connection, subject, data; reply_to)
timeout_task = Threads.@spawn :interactive begin
Base.sigatomic_begin() # `disable_sigint` is not enought here, must be sure that this task never receives interrupt
try wait(timer) catch end
drain(connection, sub)
end
errormonitor(timeout_task)
result = Msg[]
for _ in 1:nreplies
msg = next(connection, sub; no_throw = true)
isnothing(msg) && break # Do not throw when unsubscribed.
push!(result, msg)
has_error_status(msg) && break
end
result
end
"""
Request a reply from a service listening for `subject` messages. Reply is converted to specified type. Apropriate `convert` method must be defined, otherwise error is thrown.
"""
function request(
T::Type,
connection::Connection,
subject::String,
data = nothing;
timer::Timer = Timer(parse(Float64, get(ENV, "NATS_REQUEST_TIMEOUT_SECONDS", string(DEFAULT_REQUEST_TIMEOUT_SECONDS))))
)
find_msg_conversion_or_throw(T)
result = request(connection, subject, data; timer)
convert(T, result)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 8973 | using Test
using Random
using NATS
@show Threads.nthreads()
@show Threads.nthreads(:interactive)
@show Threads.nthreads(:default)
include("util.jl")
@testset "Warmup" begin
connection = NATS.connect()
empty!(connection.fallback_handlers)
c = Channel(1000000)
subject = "SOME_SUBJECT"
time_to_wait_s = 1.0
tm = Timer(time_to_wait_s)
sub = subscribe(connection, subject) do msg
if isopen(tm)
try put!(c, msg) catch err @error err end
end
end
publish(connection, subject, "Hi!")
drain(connection, sub)
close(c)
NATS.status()
end
@testset "Pub-sub latency" begin
nc = NATS.connect()
published_time = 0.0
received_time = 0.0
nsamples = 26
with_connection(nc) do
subscribe("latency") do msg
received_time = time()
end
latencies = []
for i in 1:nsamples
published_time = time()
publish("latency", "This is payload!")
sleep(0.25)
diff = 1000 * (received_time - published_time)
i == 1 || push!(latencies, diff) # skip first - compilation included
end
@info "Latencies in ms: $(round.(latencies, digits = 2))"
@info "min: $(minimum(latencies)), max: $(maximum(latencies)), avg: $(sum(latencies)/length(latencies))"
end
drain(nc)
end
@testset "Request-reply latency" begin
nc = NATS.connect()
published_time = 0.0
received_time = 0.0
nsamples = 26
with_connection(nc) do
reply("latency") do msg
return "This is a reply!"
end
latencies = []
for i in 1:nsamples
@timed _, tm = @timed request("latency", "This is request!")
i == 1 || push!(latencies, 1000*tm)
end
@info "Latencies in ms: $(round.(latencies, digits = 2))"
@info "min: $(minimum(latencies)), max: $(maximum(latencies)), avg: $(sum(latencies)/length(latencies))"
end
drain(nc)
end
function msgs_per_second(connection::NATS.Connection, connection2::NATS.Connection, spawn = false)
empty!(connection.fallback_handlers)
c = Channel(100000000)
subject = "SOME_SUBJECT"
time_to_wait_s = 10.0
tm = Timer(time_to_wait_s)
msgs_after_timeout = Threads.Atomic{Int64}(0)
time_first_pub = 0.0
time_first_msg = 0.0
sub = subscribe(connection, subject; spawn) do msg
if time_first_msg == 0.0
time_first_msg = time()
end
if isopen(tm)
try put!(c, msg) catch err @error err end
else
Threads.atomic_add!(msgs_after_timeout, 1)
end
end
sleep(1)
t = Threads.@spawn :default begin
@time while isopen(tm)
if time_first_pub == 0.0
time_first_pub = time()
end
publish(connection2, subject, "Hi!")
# NATS.send(connection2, pub)
end
drain(connection, sub)
end
errormonitor(t)
# @async interactive_status(tm)
wait(t)
received = Base.n_avail(c)
@info "Received $received messages in $time_to_wait_s s, $(received / time_to_wait_s) msgs / s."
NATS.status()
@show connection.stats connection2.stats msgs_after_timeout[]
@show (time_first_msg - time_first_pub)
sleep(1)
end
@testset "Msgs per second." begin
connection = NATS.connect()
msgs_per_second(connection, connection)
end
@testset "Msgs per second with async handlers." begin
connection = NATS.connect()
msgs_per_second(connection, connection, true)
end
@testset "Requests per second with sync handlers." begin
sleep(5) # Wait for buffers flush from previous tests.
connection = NATS.connect()
subject = randstring(5)
sub = reply(connection, subject) do msg
"This is a reply."
end
counter = 0
tm = Timer(1.0)
while isopen(tm)
res = request(connection, subject)
counter = counter + 1
end
drain(connection, sub)
@info "Sync handlers: $counter requests / second."
NATS.status()
end
@testset "Requests per second with async handlers." begin
connection = NATS.connect()
subject = randstring(5)
sub = reply(connection, subject; spawn = true) do msg
"This is a reply."
end
counter = 0
tm = Timer(1.0)
while isopen(tm)
res = request(connection, subject)
counter = counter + 1
end
drain(connection, sub)
@info "Async handlers: $counter requests / second."
NATS.status()
end
@testset "External requests per second." begin
connection = NATS.connect()
counter = 0
tm = Timer(1.0)
response = try request(connection, "help.please") catch err; err end
if response isa NATSError && response.code == 503
@info "No external service working, skipping test"
return
end
while isopen(tm)
res = request(connection, "help.please")
counter = counter + 1
end
@info "Exteranal service: $counter requests / second."
NATS.status()
end
@testset "Publisher benchmark." begin
connection = NATS.connect()
tm = Timer(1.0)
counter = 0
c = 0
while isopen(tm)
publish(connection, "zxc", "Hello world!!!!!")
counter = counter + 1
c += 1
if c == 10000
c = 0
yield()
end
end
@info "Published $counter messages."
end
@testset "Publisher benchmark with `nats bench`" begin
docker_network = get(ENV, "TEST_JOB_CONTAINER_NETWORK", nothing)
if isnothing(docker_network)
@info "No docker network specified, skipping benchmarks"
return
end
conn = NATS.connect()
n = 1000000
t = @async begin
cmd = `docker run --network $docker_network -e GITHUB_ACTIONS=true -e CI=true --entrypoint nats synadia/nats-box:latest --server nats:4222 bench foo --sub 1 --pub 0 --size 16 --msgs $n`
io = IOBuffer();
result = run(pipeline(cmd; stdout = io))
# result.exitcode == 0 || error(" $cmd failed with $(result.exitcode)")
output = String(take!(io))
println(output)
end
sleep(1)
first_msg_time = time()
for i in 1:n
publish(conn, "foo", "This is payload!")
end
last_msg_time = time()
try
wait(t)
finally
drain(conn)
end
sleep(1)
@show conn.stats
total_time = last_msg_time - first_msg_time
@info "Performance is $( n / total_time) msgs/sec"
end
@testset "Subscriber benchmark with `nats bench`" begin
docker_network = get(ENV, "TEST_JOB_CONTAINER_NETWORK", nothing)
if isnothing(docker_network)
@info "No docker network specified, skipping benchmarks"
return
end
conn = NATS.connect()
n = 1000000
received_count = 0
first_msg_time = 0.0
last_msg_time = 0.0
sub = subscribe(conn, "foo") do msg
if first_msg_time == 0.0
first_msg_time = time()
end
received_count += 1
if received_count == n
last_msg_time = time()
end
end
sleep(0.1) # Give server time to process sub.
t = @async begin
cmd = `docker run --network $docker_network -e GITHUB_ACTIONS=true -e CI=true --entrypoint nats synadia/nats-box:latest --server nats:4222 bench foo --pub 1 --size 16 --msgs $n`
io = IOBuffer();
result = run(pipeline(cmd; stdout = io))
# result.exitcode == 0 || error(" $cmd failed with $(result.exitcode)")
output = String(take!(io))
println(output)
end
try
wait(t)
finally
drain(conn)
end
sleep(1)
@show conn.stats
total_time = last_msg_time - first_msg_time
@info "Received $received_count messages from $n expected"
if received_count == n
@info "Performance is $( n / total_time) msgs/sec"
end
end
@testset "Benchmark msgs / sec roundtrip" begin
nc = NATS.connect()
function subscribe_until_timeout(nc::NATS.Connection, timeout = 1.0)
tm = Timer(timeout)
counter = 0
start = nothing
sub = subscribe(nc, "foo") do
if isnothing(start)
start = time()
end
counter += 1
end
wait(tm)
unsubscribe(nc, sub)
if counter == 0
@info "No messages"
else
@info "Processed $counter messages in $(time() - start) s. $(counter / (time() - start)) msgs/sec)"
end
counter
end
bench_task = @async begin
sub_task = Threads.@spawn :default subscribe_until_timeout(nc, 1.0)
Threads.@spawn :default while !istaskdone(sub_task)
publish(nc, "foo", "This is payload!")
end
wait(sub_task)
sub_task.result
end
_, tm = @timed wait(bench_task);
received_messages = bench_task.result
@info "$(received_messages / tm) msgs / sec"
end | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 2706 | using Test
using NATS
try
NATS.connect(default = true)
catch
@info "Default conneciton already exists."
end
@testset "Single message" begin
ch = NATSChannel{String}(subject = "channel_subject")
@async put!(ch, "Simple payload")
res = take!(ch)
@test res == "Simple payload"
end
@testset "Test blocking" begin
ch = NATSChannel{String}(subject = "channel_subject")
@async put!(ch, "This is test")
sleep(3)
res = take!(ch)
@test res == "This is test"
res = nothing
t = @async begin
res = take!(ch)
end
sleep(3)
put!(ch, "Another test")
wait(t)
@test res == "Another test"
end
@testset "1K messages put! first" begin
ch = NATSChannel{String}(subject = "channel_subject")
n=1000
for i in 1:n
@async put!(ch, "$i")
end
results = String[]
@sync for i in 1:n
@async begin
res = take!(ch)
push!(results, res)
end
end
@test length(results) == n
for i in 1:n
@test "$i" in results
end
end
@testset "1K messages take! first" begin
ch = NATSChannel{String}(subject = "channel_subject")
n = 1000
results = String[]
for i in 1:n
@async begin
res = take!(ch)
push!(results, res)
end
end
@sync for i in 1:n
@async put!(ch, "$i")
end
@test length(results) == n
for i in 1:n
@test "$i" in results
end
end
@testset "Multiple connections" begin
conn1 = NATS.connect()
conn2 = NATS.connect()
conn3 = NATS.connect()
conn4 = NATS.connect()
conn5 = NATS.connect()
ch1 = NATSChannel{String}(subject = "channel_subject", connection = conn1)
ch2 = NATSChannel{String}(subject = "channel_subject", connection = conn2)
ch3 = NATSChannel{String}(subject = "channel_subject", connection = conn3)
ch4 = NATSChannel{String}(subject = "channel_subject", connection = conn4)
ch5 = NATSChannel{String}(subject = "channel_subject", connection = conn5)
for i in 1:15
@async put!(ch1, "$i")
end
for i in 1:15
@async put!(ch2, "$(15 + i)")
end
lk = ReentrantLock()
results = String[]
for i in 1:10
@async begin
res = take!(ch3)
@lock lk push!(results, res)
end
end
for i in 1:10
@async begin
res = take!(ch4)
@lock lk push!(results, res)
end
end
for i in 1:10
@async begin
res = take!(ch5)
@lock lk push!(results, res)
end
end
sleep(2)
@test length(results) == 30
for i in 1:30
@test "$i" in results
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 7578 | using Test
using NATS
using Random
function find_nats_container_id()
io = IOBuffer();
run(pipeline(`docker ps -f name=nats -q`; stdout = io))
output = String(take!(io))
container_id = split(output, '\n')[1]
container_id
end
function restart_nats_server(container_id = find_nats_container_id())
cmd = `docker container restart $container_id`
@info "Cmd is $cmd"
result = run(cmd)
if result.exitcode == 0
@info "Restarted NATS server."
else
@warn "Cannot restart NATS server, exit code from $cmd was $(result.exitcode)."
end
result.exitcode
end
function stop_nats_server(container_id = find_nats_container_id())
cmd = `docker stop $container_id`
@info "Cmd is $cmd"
result = run(cmd)
if result.exitcode == 0
@info "Stopped NATS server."
else
@warn "Cannot stop NATS server, exit code from $cmd was $(result.exitcode)."
end
result.exitcode
end
function start_nats_server(container_id = find_nats_container_id())
cmd = `docker start $container_id`
@info "Cmd is $cmd"
result = run(cmd)
if result.exitcode == 0
@info "Started NATS server."
else
@warn "Cannot start NATS server, exit code from $cmd was $(result.exitcode)."
end
result.exitcode
end
nc = NATS.connect()
@testset "Reconnecting." begin
@test restart_nats_server() == 0
sleep(10)
@test nc.status == NATS.CONNECTED
resp = request(nc, "help.please")
@test resp isa NATS.Msg
end
# @testset "Close outbox when messages pending." begin
# nc = NATS.connect()
# c = Channel()
# subject = randstring(10)
# sub = subscribe(subject) do msg
# put!(c, msg)
# end
# publish("SOME.BAR"; payload = "Hi!")
# publish("SOME.BAR"; payload = "Hi!")
# publish("SOME.BAR"; payload = "Hi!")
# close(nc.outbox)
# sleep(5)
# result = take!(c)
# @test result isa NATS.Msg
# @test payload(result) == "Hi!"
# @test length(NATS.state.handlers) == 1
# unsubscribe(sub)
# sleep(0.1)
# @test length(NATS.state.handlers) == 0
# end
@testset "Subscribtion survive reconnect." begin
c = Channel(100)
subject = randstring(5)
sub = subscribe(nc, subject) do msg
put!(c, msg)
end
sleep(0.5)
@test restart_nats_server() == 0
sleep(5)
@test nc.status == NATS.CONNECTED
publish(nc, subject, "Hi!")
sleep(5)
@test Base.n_avail(c) == 1
end
@testset "Reconnect during request." begin
subject = randstring(5)
sub = reply(nc, subject) do msg
sleep(5)
"This is a reply."
end
t = @async begin
sleep(1)
restart_nats_server()
end
rep = request(nc, subject; timer = Timer(20))
@test payload(rep) == "This is a reply."
@test nc.status == NATS.CONNECTED
rep = request(nc, subject; timer = Timer(20))
@test payload(rep) == "This is a reply."
@test t.result == 0
end
@testset "4K requests" begin
nats_container_id = find_nats_container_id()
@info "NATS container is $nats_container_id"
@async interactive_status(tm)
n = 400 # TODO: restore 4k
subject = @lock NATS.state.lock randstring(5)
cnt = Threads.Atomic{Int64}(0)
sub = reply(nc, subject, spawn = true) do msg
sleep(10 * rand())
Threads.atomic_add!(cnt, 1)
"This is a reply."
end
results = Channel(n)
cond = Channel()
for _ in 1:n
t = Threads.@spawn :default begin
msg = request(nc, subject; timer=Timer(20))
put!(results, msg)
if Base.n_avail(results) == n
close(cond)
close(results)
end
end
errormonitor(t)
end
@async begin sleep(60); close(cond); close(results) end
sleep(5)
@info "Received $(Base.n_avail(results)) / $n results after half of time. "
@test restart_nats_server(nats_container_id) == 0
if !haskey(ENV, "CI")
@async interactive_status(cond)
end
try take!(cond) catch end
unsubscribe(nc, sub)
replies = collect(results)
# @info "Replies count is $(cnt.value)."
@info "Lost msgs: $(n - length(replies))."
@test length(replies) > 0.8 * n # TODO: it fails a lot for TLS
@test all(r -> payload(r) == "This is a reply.", replies)
NATS.status()
end
@testset "4K requests with request retry." begin
nats_container_id = find_nats_container_id()
@info "NATS container is $nats_container_id"
@async interactive_status(tm)
n = 400 # TODO: restore 4k
subject = @lock NATS.state.lock randstring(5)
cnt = Threads.Atomic{Int64}(0)
sub = reply(nc, subject, spawn = true) do msg
# sleep(2 * rand())
Threads.atomic_add!(cnt, 1)
"This is a reply."
end
results = Channel(n)
cond = Channel()
for _ in 1:n
t = Threads.@spawn :default begin
delays = rand(3.0:0.1:5.0, 15)
msg = retry(request; delays)(nc, subject; timer=Timer(5))
put!(results, msg)
if Base.n_avail(results) == n
close(cond)
close(results)
end
end
errormonitor(t)
end
@async begin sleep(120); close(cond); close(results) end
sleep(2)
@info "Received $(Base.n_avail(results)) / $n results after half of time. "
@test restart_nats_server(nats_container_id) == 0
if !haskey(ENV, "CI")
@async interactive_status(cond)
end
try take!(cond) catch end
unsubscribe(nc, sub)
replies = collect(results)
# @info "Replies count is $(cnt.value)."
@info "Lost msgs: $(n - length(replies))."
@test length(replies) == n
@test all(r -> payload(r) == "This is a reply.", replies)
NATS.status()
end
@testset "Disconnect during heavy publications." begin
received_count = Threads.Atomic{Int64}(0)
published_count = Threads.Atomic{Int64}(0)
subject = "pub_subject"
sub = subscribe(nc, subject) do msg
Threads.atomic_add!(received_count, 1)
end
sleep(0.5)
pub_task = Threads.@spawn begin
for i in 1:10000
timer = Timer(0.001)
for _ in 1:10
publish(nc, subject, "Hi!")
end
Threads.atomic_add!(published_count, 10)
try wait(timer) catch end
end
@info "Publisher finished."
end
sleep(2)
@info "Published: $(published_count.value), received: $(received_count.value)."
@test restart_nats_server() == 0
sleep(2)
@info "Published: $(published_count.value), received: $(received_count.value)."
@test restart_nats_server() == 0
sleep(2)
@info "Published: $(published_count.value), received: $(received_count.value)."
@test restart_nats_server() == 0
wait(pub_task)
sleep(4) # wait for published messages
unsubscribe(nc, sub)
@info "Published: $(published_count.value), received: $(received_count.value)."
end
@testset "Reconnecting after disconnect." begin
container_id = find_nats_container_id()
nc = NATS.connect(; reconnect_delays = [])
@test stop_nats_server(container_id) == 0
sleep(5)
@test nc.status == NATS.DISCONNECTED
@test start_nats_server(container_id) == 0
sleep(5)
NATS.reconnect(nc)
sleep(10)
@test nc.status == NATS.CONNECTED
end
@testset "Disconnecting when retries exhausted." begin
nc = NATS.connect(; reconnect_delays = [])
@test stop_nats_server() == 0
sleep(5)
@test nc.status == NATS.DISCONNECTED
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 5478 | using Test
using NATS
using Random
@info "Running with $(Threads.nthreads()) threads."
function find_container_id(name)
io = IOBuffer();
cmd = `docker ps -f name=$name -q`
result = run(pipeline(cmd; stdout = io))
result.exitcode == 0 || error(" $cmd failed with $(result.exitcode)")
output = String(take!(io))
container_id = only(split(output, '\n'; keepempty=false))
container_id
end
port_to_container = Dict(
4222 => find_container_id("nats-node-1"),
4223 => find_container_id("nats-node-2"),
4224 => find_container_id("nats-node-3")
)
function signal_lame_duck_mode(container_id)
cmd = `docker exec $container_id nats-server --signal ldm=1`
result = run(cmd)
result.exitcode == 0 || error(" $cmd failed with $(result.exitcode)")
end
function start_container(container_id)
cmd = `docker start $container_id`
result = run(cmd)
result.exitcode == 0 || error(" $cmd failed with $(result.exitcode)")
end
@testset "Request during node switch" begin
connection = NATS.connect("localhost:4222")
sub = reply(connection, "a_topic"; spawn = true) do msg
sleep(7)
"This is a reply."
end
errormonitor(@async begin
sleep(2)
signal_lame_duck_mode(port_to_container[4222])
end)
start_time = time()
response = request(String, connection, "a_topic", timer = Timer(15))
@info "Response time was $(time() - start_time)"
@test response == "This is a reply."
@show connection.url
@test !endswith(connection.url, ":4222")
sleep(15) # Wait at least 10 s for server exit
start_container(port_to_container[4222])
sleep(10)
@test "localhost:4222" in connection.info.connect_urls
drain(connection)
end
@testset "No messages lost during node switch." begin
pub_conn = NATS.connect("localhost:4222") # TODO: unclear why echo needs to be false to not have doubled msgs.
sub_conn = NATS.connect("localhost:4223")
sub_conn_received_count = 0
sub_conn_results = []
sub1 = subscribe(sub_conn, "a_topic"; spawn = false) do msg
sub_conn_received_count = sub_conn_received_count + 1
push!(sub_conn_results, payload(msg))
end
pub_conn_received_count = 0
pub_conn_results = []
sub2 = subscribe(pub_conn, "a_topic"; spawn = false) do msg
pub_conn_received_count = pub_conn_received_count + 1
push!(pub_conn_results, payload(msg))
end
sleep(0.5) # TODO: this sleep should be removed?
errormonitor(@async begin
sleep(2)
signal_lame_duck_mode(port_to_container[4222])
end)
n = 1500
start_time = time()
for i in 1:n
publish(pub_conn, "a_topic", "$i")
sleep(0.001)
end
@info "Published $n messages in $(time() - start_time) seconds."
sleep(0.1)
@info "Distrupted connection received $pub_conn_received_count msgs."
@test pub_conn_received_count > n - 5
@test pub_conn_received_count <= n
@test unique(pub_conn_results) == pub_conn_results
@show first(pub_conn_results) last(pub_conn_results)
@test sub_conn_received_count == n
@test unique(sub_conn_results) == sub_conn_results
@show first(sub_conn_results) last(sub_conn_results)
sleep(15) # Wait at least 10 s for server exit
start_container(port_to_container[4222])
sleep(10)
drain(pub_conn)
drain(sub_conn)
@show NATS.state.stats
end
@testset "Lame Duck Mode during heavy publications" begin
connection = NATS.connect("localhost:4222")
subscription_connection = NATS.connect("localhost:4224")
received_count = Threads.Atomic{Int64}(0)
published_count = Threads.Atomic{Int64}(0)
subject = "pub_subject"
sub = subscribe(subscription_connection, subject) do msg
Threads.atomic_add!(received_count, 1)
end
sleep(0.5)
pub_task = Threads.@spawn begin
# publishes 100k msgs / s for 10s (roughly)
for i in 1:10000
timer = Timer(0.001)
for _ in 1:100
publish(connection, subject, "Hi!")
end
Threads.atomic_add!(published_count, 100)
try wait(timer) catch end
end
@info "Publisher finished."
end
sleep(2)
@info "Published: $(published_count.value), received: $(received_count.value)."
sleep(2)
signal_lame_duck_mode(port_to_container[4222])
while !istaskdone(pub_task)
sleep(2)
@info "Published: $(published_count.value), received: $(received_count.value)."
end
sleep(5) # Wait all messages delivered
unsubscribe(connection, sub)
@info "Published: $(published_count.value), received: $(received_count.value)."
@test published_count[] == received_count.value[]
sleep(15) # Wait at least 10 s for server exit
start_container(port_to_container[4222])
sleep(10)
@test "localhost:4222" in connection.info.connect_urls
drain(connection)
end
# @testset "Switch sub connection." begin
# conn_a = NATS.connect("localhost", 4222)
# conn_b = NATS.connect("localhost", 4223)
# subject = "switch"
# sub = subscribe(subject; connection = conn_a) do msg
# @show msg
# end
# @async for i in 1:10
# publish(subject; payload = "$i", connection = conn_a)
# sleep(1)
# end
# sleep(5)
# unsubscribe(sub; connection = conn_a)
# NATS.send(conn_b, sub)
# # unsubscribe(sub; connection = conn_a)
# end | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 7857 |
using Test
using NATS
using Random
using ScopedValues
using StructTypes
NATS.status()
nc = NATS.connect()
@testset "Ping" begin
ping(nc)
@test true # TODO: add pong count to connection stats
end
NATS.status()
@testset "Show connection status" begin
@test startswith(repr(nc), "NATS.Connection(")
end
NATS.status()
@testset "Publication subscription stats should be counted from nested spawned task." begin
conn = NATS.connect()
sub = subscribe(conn, "stats_test") do
Threads.@spawn begin
Threads.@spawn publish(conn, "some_other_subject", "Some payload")
end
end
sleep(0.2)
publish(conn, "stats_test")
sleep(0.2)
@test conn.stats.msgs_published == 2
sub_stats = conn.sub_data[sub.sid].stats
@test sub_stats.msgs_published == 1
drain(conn, sub)
end
NATS.status()
@testset "Method error hints." begin
@test_throws "Conversion of NATS message into type Float64 is not defined" subscribe(nc, "SOME.THING") do msg::Float64 end
@test_throws "Conversion of type Int64 to NATS payload is not defined." request(nc, "SOME.REQUESTS", 4)
@test_throws "Conversion of type Int64 to NATS payload is not defined." request(nc, 4, "SOME.REQUESTS", 4)
@test_throws "Conversion of NATS message into type Integer is not defined." reply(nc, "SOME.REQUESTS") do msg::Integer
"Received $msg"
end
end
@testset "Connection url schemes" begin
try
@test_throws Base.IOError NATS.connect("tls://localhost:4321")
conn = NATS.connect("nats://username:passw0rd@localhost:4222")
@test NATS.status(conn) == NATS.CONNECTED
conn = NATS.connect("nats://localhost:4321,localhost:5555", retry_on_init_fail = true)
@test NATS.status(conn) == NATS.CONNECTING
drain(conn)
@test_throws ErrorException NATS.connect(":4321")
conn = NATS.connect("localhost")
@test NATS.status(conn) == NATS.CONNECTED
conn = NATS.connect("localhost:4321,localhost:4322,localhost:4222", retry_on_init_fail = true, retain_servers_order = true, reconnect_delays = [0.1, 0.1, 0.1])
sleep(1)
@test conn.reconnect_count == 1
@test conn.connect_init_count == 3
catch
# This may fail for some NATS server setup and this is ok.
@info "`Connection url schemes` tests ignored."
end
end
NATS.status()
@testset "Handler error throttling." begin
subject = randstring(8)
sub = subscribe(nc, subject) do msg
error("Just testing...")
end
tm = Timer(7)
while isopen(tm)
publish(nc, subject, "Hi!")
sleep(0.1)
end
drain(nc, sub)
end
NATS.status()
@testset "Handler error throttling async." begin
subject = randstring(8)
sub = subscribe(nc, subject, spawn = true) do msg
error("Just testing...")
end
tm = Timer(7)
while isopen(tm)
publish(nc, subject, "Hi!")
sleep(0.1)
end
drain(nc, sub)
end
NATS.status()
@testset "Should reconnect on malformed msg" begin
options = merge(NATS.default_connect_options(), (protocol=100,) )
con_msg = StructTypes.constructfrom(Connect, options)
NATS.send(nc, con_msg)
sleep(10)
@test nc.status == NATS.CONNECTED
end
NATS.status()
@testset "Should reconnect on send buffer closed" begin
NATS.reopen_send_buffer(nc)
sleep(5)
@test nc.status == NATS.CONNECTED
end
NATS.status()
@testset "Draining connection." begin
nc = NATS.connect()
subject = "DRAIN_TEST"
sub = subscribe(nc, "DRAIN_TEST") do msg end
@test length(nc.sub_data) == 1
NATS.drain(nc)
@test isempty(nc.sub_data)
@test_throws ErrorException publish(nc, "DRAIN_TEST")
@test_throws ErrorException ping(nc)
@test NATS.status(nc) == NATS.DRAINED
NATS.drain(nc) # Draining drained connection is noop.
@test NATS.status(nc) == NATS.DRAINED
@test isempty(nc.sub_data)
end
NATS.status()
@testset "Connections API" begin
@test NATS.connection(1) isa NATS.Connection
@test_throws ErrorException NATS.connection(10000000)
end
NATS.status()
@testset "Connect error from protocol init when options are wrong" begin
@test_throws "invalid client protocol" NATS.connect(protocol = 100)
@test_throws "Client requires TLS but it is not available for the server." NATS.connect(tls_required = true)
end
NATS.status()
@testset "Subscription warnings" begin
NATS.status()
sub1 = subscribe(nc, "too_many_handlers", spawn = true, monitoring_throttle_seconds = 15.0) do msg
sleep(21)
end
for _ in 1:1001
publish(nc, "too_many_handlers")
end
sub2 = subscribe(nc, "overload_channel", spawn = false, channel_size = 100, monitoring_throttle_seconds = 15.0) do msg
sleep(21)
end
for _ in 1:82
publish(nc, "overload_channel")
sleep(0.01) # Sleep causes that msga are not batches.
end
sleep(21)
unsubscribe(nc, sub1)
unsubscribe(nc, sub2)
NATS.status()
sub3 = subscribe(nc, "overload_channel", spawn = false, channel_size = 10) do msg
sleep(5)
end
for _ in 1:15
publish(nc, "overload_channel")
sleep(0.01) # Sleep causes that msga are not batches.
end
sleep(5)
unsubscribe(nc, sub3)
NATS.status()
end
NATS.status()
@testset "Send buffer overflow" begin
connection = NATS.connect(send_buffer_limit = 5, send_retry_delays = [])
@test_throws ErrorException for _ in 1:100
publish(connection, "overflow_buffer", "some long payload to overflow buffer")
end
NATS.ping(connection) # Ping should work even when buffer is overflown
connection = NATS.connect(send_buffer_limit = 5)
counter = 0
sub = subscribe(connection, "overflow_buffer") do msg
counter += 1
end
for _ in 1:100
publish(connection, "overflow_buffer", "test retry path")
end
sleep(1)
unsubscribe(connection, sub)
@test counter > 90
end
NATS.status()
@testset "Publish on drained connection fails" begin
connection = NATS.connect()
@async NATS.drain(connection)
sleep(0.1)
@test_throws ErrorException publish(connection, "test_publish_on_drained")
pub = NATS.Pub("test_publish_on_drained", nothing, 0, UInt8[])
@test_throws ErrorException NATS.send(connection, repeat([pub], 10))
end
NATS.status()
@testset "Subscription draining" begin
connection = NATS.connect()
published_count = 0
delivered_count = 0
sub = subscribe(connection, "some_topic") do msg
sleep(0.1)
delivered_count += 1
end
sleep(1) # Let server to notice subscribtion.
publisher = @async for i in 1:300
publish(connection, "some_topic", "Hi!")
published_count += 1
sleep(0.01)
end
sleep(0.2)
drain(connection, sub)
sleep(1)
@test delivered_count > 0
wait(publisher)
@show delivered_count published_count
@test connection.stats.msgs_handled == delivered_count
@test connection.stats.msgs_received == delivered_count
end
NATS.status()
@testset "Connection draining" begin
connection = NATS.connect()
published_count = 0
delivered_count = 0
sub = subscribe(connection, "some_topic") do msg
sleep(0.05)
delivered_count += 1
end
sleep(1) # Let server to notice subscription.
publisher = @async for i in 1:300
publish(connection, "some_topic", "Hi!")
published_count += 1
sleep(0.01)
end
sleep(0.3)
@time drain(connection)
sleep(1)
@test delivered_count > 0
@test_throws "Cannot send on connection with status DRAINING" wait(publisher)
@show delivered_count published_count
@test connection.stats.msgs_handled == delivered_count
@test connection.stats.msgs_received == delivered_count
end
NATS.status()
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1930 | using NATS, Test
using JSON3
@testset "Scoped connections" begin
@test_throws ErrorException publish("some.random.subject")
sc = NATS.connect()
was_delivered = false
with_connection(sc) do
sub = subscribe("subject_1") do msg
was_delivered = true
end
publish("subject_1")
publish("subject_1", "Some data")
drain(sub)
end
@test was_delivered == true
with_connection(sc) do
sub = reply("service_1") do
"Response content"
end
answer = request("service_1")
@test payload(answer) == "Response content"
answer = request(String, "service_1")
@test answer == "Response content"
sub2 = reply("service_1") do
"Response content 2"
end
answers = request(2, "service_1", nothing)
@test length(answers) == 2
drain(sub)
drain(sub2)
end
drain(sc)
sc = NATS.connect()
with_connection(sc) do
sub1 = reply("some_service") do
"Response content"
end
sub2 = reply("some_service") do
"Response content"
end
unsubscribe(sub1)
unsubscribe(sub2.sid)
end
drain(sc)
end
@testset "Scoped connections sync subscriptions" begin
sc = NATS.connect()
with_connection(sc) do
sub = subscribe("subject_1")
publish("subject_1", "test")
msg = next(sub)
@test msg isa NATS.Msg
publish("subject_1", "{}")
msg = next(JSON3.Object, sub)
@test msg isa JSON3.Object
publish("subject_1", "test")
msgs = next(sub, 1)
@test msgs isa Vector{NATS.Msg}
@test length(msgs) == 1
publish("subject_1", "{}")
jsons = next(JSON3.Object, sub, 1)
@test jsons isa Vector{JSON3.Object}
@test length(jsons) == 1
drain(sub)
end
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 904 |
using Test
using NATS
@testset "Test fallback handler" begin
sub = subscribe(nc, "SOME.BAR") do msg
@show msg
end
empty!(nc.sub_data) # Break state of connection to force fallback handler.
publish(nc, "SOME.BAR", "Hi!")
sleep(2) # Wait for compilation.
@test nc.stats.msgs_dropped > 0
drain(nc, sub)
end
NATS.status()
@testset "Test custom fallback handler" begin
empty!(nc.fallback_handlers)
was_called = false
NATS.install_fallback_handler(nc) do nc, msg
was_called = true
@info "Custom fallback called." msg
end
sub = subscribe(nc, "SOME.FOO") do msg
@show msg
end
empty!(nc.sub_data) # Break state of connection to force fallback handler.
publish(nc, "SOME.FOO", "Hi!")
sleep(0.5) # Wait for compilation.
@test nc.stats.msgs_dropped > 0
@test was_called
drain(nc, sub)
end
NATS.status()
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 309 |
using NATS
function main()
nc = NATS.connect()
subscribe(nc, "test_subject") do x
@show x
end
while true
sleep(5)
try
publish(nc, "test_subject")
catch
break
end
end
sleep(10)
end
disable_sigint() do
main()
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 13224 | using Test
using NATS
using NATS.JetStream
using Random
using Sockets
@info "Running with $(Threads.nthreads()) threads."
function have_nats()
try
Sockets.getaddrinfo(get(ENV, "NATS_HOST", "localhost"))
nc = NATS.connect()
@assert nc.status == NATS.CONNECTED
@assert NATS.info(nc).jetstream == true
@info "JetStream avaliable, running connected tests."
true
catch err
@info "JetStream unavailable, skipping connected tests." err
false
end
end
@testset "Should be connected to JetStream" begin
@test have_nats()
end
@testset "Create stream and delete stream." begin
connection = NATS.connect()
stream_config = StreamConfiguration(
name = "SOME_STREAM",
description = "SOME_STREAM stream",
subjects = ["SOME_STREAM.*"],
retention = :workqueue,
storage = :memory,
)
stream_info = JetStream.stream_create(connection, stream_config)
@test stream_info isa JetStream.StreamInfo
names = JetStream.stream_names(connection, "SOME_STREAM.*")
@test "SOME_STREAM" in names
@test length(names) == 1
stream_delete(connection, stream_info)
names = JetStream.stream_names(connection, "SOME_STREAM.*")
@test !("SOME_STREAM" in names)
stream_info = stream_update_or_create(connection, stream_config)
stream_info = stream_update(connection, stream_config)
stream_purge(connection, stream_info)
stream_delete(connection, stream_info)
end
@testset "Stream subscriptions" begin
connection = NATS.connect()
stream_config = StreamConfiguration(
name = "SOME_STREAM",
description = "SOME_STREAM stream",
subjects = ["SOME_STREAM.*"],
)
stream_info = JetStream.stream_create(connection, stream_config)
n = 3
for i in 1:n
stream_publish(connection, "SOME_STREAM.foo", "test $i")
end
results = []
stream_sub = stream_subscribe(connection, "SOME_STREAM.foo") do msg
push!(results, msg)
end
@test repr(stream_sub) == "StreamSub(\"SOME_STREAM.foo\")"
sleep(0.5)
stream_unsubscribe(connection, stream_sub)
@test length(results) == n
stream_delete(connection, stream_info)
@test_throws "No stream found for subject" stream_subscribe(connection, "NOT_EXISTS.foo") do msg
@info msg
end
end
@testset "Stream message access" begin
connection = NATS.connect()
stream_config = StreamConfiguration(
name = "SOME_STREAM",
description = "SOME_STREAM stream",
subjects = ["SOME_STREAM.*"],
retention = :workqueue,
storage = :memory,
)
stream_info = stream_create(connection, stream_config)
@test_throws "no message found" stream_message_get(connection, stream_info, "SOME_STREAM.not_existing")
stream_publish(connection, "SOME_STREAM.msg1", ("some msg", ["a" => "xy"]))
received = stream_message_get(connection, stream_info, "SOME_STREAM.msg1")
@test NATS.payload(received) == "some msg"
@test NATS.header(received, "a") == "xy"
@test !haskey(connection.allow_direct, "SOME_STREAM")
received = stream_message_get(connection, "SOME_STREAM", "SOME_STREAM.msg1")
@test haskey(connection.allow_direct, "SOME_STREAM")
received = stream_message_get(connection, "SOME_STREAM", "SOME_STREAM.msg1")
@test NATS.payload(received) == "some msg"
@test NATS.header(received, "a") == "xy"
stream_message_delete(connection, stream_info, received)
@test_throws "not found" stream_message_delete(connection, stream_info, received)
# The same but with `allow_direct`
stream_config = StreamConfiguration(
name = "SOME_STREAM",
description = "SOME_STREAM stream",
subjects = ["SOME_STREAM.*"],
retention = :workqueue,
storage = :memory,
allow_direct = true
)
@test_throws "stream name already in use with a different configuration" stream_create(connection, stream_config)
stream_delete(connection, stream_info)
stream_info = stream_create(connection, stream_config)
@test_throws NATSError stream_message_get(connection, stream_info, "SOME_STREAM.not_existing")
stream_publish(connection, "SOME_STREAM.msg1", ("some msg", ["a" => "xy"]))
received = stream_message_get(connection, stream_info, "SOME_STREAM.msg1")
@test NATS.payload(received) == "some msg"
@test NATS.header(received, "a") == "xy"
stream_message_delete(connection, stream_info, received)
@test_throws "not found" stream_message_delete(connection, stream_info, received)
stream_delete(connection, stream_info)
end
@testset "Invalid stream name." begin
connection = NATS.connect()
stream_config = StreamConfiguration(
name = "SOME*STREAM",
description = "Stream with invalid name",
subjects = ["SOME_STREAM.*"],
)
@test_throws ErrorException JetStream.stream_create(connection, stream_config)
end
@testset "Create stream, publish and subscribe." begin
connection = NATS.connect()
stream_name = randstring(10)
subject_prefix = randstring(4)
stream_config = StreamConfiguration(
name = stream_name,
description = "Test generated stream.",
subjects = ["$subject_prefix.*"],
retention = :limits,
storage = :memory,
metadata = Dict("asdf" => "aaaa")
)
stream_info = JetStream.stream_create(connection, stream_config)
@test stream_info isa JetStream.StreamInfo
# TODO: fix this
# @test_throws ErrorException JetStream.create(connection, stream_config)
NATS.publish(connection, "$subject_prefix.test", "Publication 1")
NATS.publish(connection, "$subject_prefix.test", "Publication 2")
NATS.publish(connection, "$subject_prefix.test", "Publication 3")
consumer_config = JetStream.ConsumerConfiguration(
filter_subjects=["$subject_prefix.*"],
ack_policy = :explicit,
name ="c1",
durable_name = "c1", #TODO: make it not durable
ack_wait = 5 * 10^9
)
consumer = JetStream.consumer_create(connection, consumer_config, stream_info)
for i in 1:3
msg = JetStream.consumer_next(connection, consumer, no_wait = true)
consumer_ack(connection, msg)
@test msg isa NATS.Msg
end
@test_throws NATSError @show JetStream.consumer_next(connection, consumer; no_wait = true)
JetStream.consumer_delete(connection, consumer)
end
uint8_vec(s::String) = convert.(UInt8, collect(s))
# TODO: fix this testest
# @testset "Ack" begin
# connection = NATS.connect()
# no_reply_to_msg = NATS.Msg("FOO.BAR", "9", nothing, 0, uint8_vec("Hello World"))
# @test_throws ErrorException JetStream.consumer_ack(no_reply_to_msg; connection)
# @test_throws ErrorException JetStream.consumer_nak(no_reply_to_msg; connection)
# msg = NATS.Msg("FOO.BAR", "9", "ack_subject", 0, uint8_vec("Hello World"))
# c = Channel(10)
# sub = NATS.subscribe(connection, "ack_subject") do msg
# put!(c, msg)
# end
# received = take!(c)
# JetStream.consumer_ack(received; connection)
# JetStream.consumer_nak(received; connection)
# NATS.drain(connection, sub)
# close(c)
# acks = collect(c)
# @test length(acks) == 2
# @test "-NAK" in NATS.payload.(acks)
# end
@testset "Key value - 100 keys" begin
connection = NATS.connect()
kv = JetStream.JetDict{String}(connection, "test_kv")
@test keyvalue_stream_info(connection, "test_kv") isa JetStream.StreamInfo
@test "test_kv" in keyvalue_buckets(connection)
@test length(kv) == 0
@test length(collect(kv)) == 0
@time @sync for i in 1:100
@async kv["key_$i"] = "value_$i"
end
other_conn = NATS.connect()
kv = JetStream.JetDict{String}(connection, "test_kv")
for i in 1:100
@test kv["key_$i"] == "value_$i"
end
@test length(kv) == 100
@test length(collect(kv)) == 100
@test length(keys(kv)) == 100
@test length(collect(keys(kv))) == 100
@test length(values(kv)) == 100
@test length(collect(values(kv))) == 100
keyvalue_stream_delete(connection, "test_kv")
end
@testset "Encoded keys" begin
connection = NATS.connect()
kv = JetStream.JetDict{String}(connection, "test_kv")
@test_throws "Key \"!@#%^&\" contains invalid character" kv["!@#%^&"] = "5"
keyvalue_stream_delete(connection, "test_kv")
kv = JetStream.JetDict{String}(connection, "test_kv", :base64url)
kv["!@#%^&"] = "5"
@test kv["!@#%^&"] == "5"
@test collect(kv) == ["!@#%^&" => "5"]
keyvalue_stream_delete(connection, "test_kv")
@test_throws "No `encodekey` implemented for wrongencoding encoding" JetStream.JetDict{String}(connection, "test_kv", :wrongencoding)
end
@testset "Create and delete KV bucket" begin
connection = NATS.connect()
bucket = randstring(10)
kv = JetStream.JetDict{String}(connection, bucket)
@test_throws KeyError kv["some_key"]
kv["some_key"] = "some_value"
@test kv["some_key"] == "some_value"
empty!(kv)
@test_throws KeyError kv["some_key"]
JetStream.keyvalue_stream_delete(connection, bucket)
@test_throws "stream not found" first(kv)
end
@testset "Watch kv changes" begin
connection = NATS.connect()
kv = JetStream.JetDict{String}(connection, "test_kv")
changes = []
sub = watch(kv) do change
push!(changes, change)
end
t = @async begin
kv["a"] = "1"
sleep(0.1)
kv["b"] = "2"
sleep(0.1)
delete!(kv, "a")
sleep(0.1)
kv["b"] = "3"
sleep(0.1)
kv["a"] = "4"
sleep(0.5)
end
wait(t)
stream_unsubscribe(connection, sub)
@test length(changes) == 5
@test changes == ["a" => "1", "b" => "2", "a" => nothing, "b" => "3", "a" => "4"]
keyvalue_stream_delete(connection, "test_kv")
end
@testset "Optimistic concurrency" begin
connection = NATS.connect()
kv = JetStream.JetDict{String}(connection, "test_kv")
with_optimistic_concurrency(kv) do
kv["a"] = "4"
kv["a"] = "5"
end
@async (sleep(2); kv["a"] = "6")
@test_throws "wrong last sequence" with_optimistic_concurrency(kv) do
old = kv["a"]
sleep(3)
kv["a"] = "$(old)_updated"
end
@test kv["a"] == "6"
keyvalue_stream_delete(connection, "test_kv")
end
@testset "Channel message passing" begin
connection = NATS.connect()
ch = JetChannel{String}(connection, "test_channel", 3)
@test repr(ch) == "JetChannel{String}(\"test_channel\", 3)"
put!(ch, "msg 1")
@test take!(ch) == "msg 1"
t = @async take!(ch)
sleep(5)
put!(ch, "msg 2")
wait(t)
@test t.result == "msg 2"
t = @async begin
sleep(0.5)
put!(ch, "msg 3")
sleep(0.5)
put!(ch, "msg 4")
sleep(0.5)
put!(ch, "msg 5")
sleep(0.5)
put!(ch, "msg 6")
sleep(0.5)
end
sleep(3)
@test !istaskdone(t)
@test take!(ch) == "msg 3"
wait(t)
@test istaskdone(t)
@test take!(ch) == "msg 4"
@test take!(ch) == "msg 5"
@test take!(ch) == "msg 6"
destroy!(ch)
end
@testset "Stream republish" begin
connection = NATS.connect()
stream_config = StreamConfiguration(
name = "SOME_STREAM",
description = "SOME_STREAM stream",
subjects = ["SOME_STREAM.*"],
retention = :workqueue,
storage = :memory,
republish = Republish(
src = "SOME_STREAM.foo",
dest = "REPUBLISHED.foo"
),
consumer_limits = StreamConsumerLimit(
max_ack_pending = 100,
),
)
stream_info = JetStream.stream_create(connection, stream_config)
republished = []
sub = subscribe(connection, "REPUBLISHED.foo") do msg
push!(republished, msg)
end
sleep(0.1)
stream_publish(connection, "SOME_STREAM.foo", "test message")
drain(connection, sub)
@test length(republished) == 1
stream_delete(connection, stream_info)
end
@testset "Stream mirroring" begin
connection = NATS.connect()
stream_config = StreamConfiguration(
name = "SOME_STREAM",
description = "SOME_STREAM stream",
subjects = ["SOME_STREAM.*"],
retention = :workqueue,
storage = :memory,
)
stream_info = JetStream.stream_create(connection, stream_config)
mirror_stream_config = StreamConfiguration(
name = "MIRROR_STREAM",
description = "MIRROR_STREAM stream",
storage = :memory,
sources = [ StreamSource(name = "SOME_STREAM") ]
)
mirror_stream_info = JetStream.stream_create(connection, mirror_stream_config)
mirror_consumer_config = ConsumerConfiguration(
name ="mirror_consumer_test",
ack_policy = :explicit
)
stream_publish(connection, "SOME_STREAM.foo", "test message")
consumer_info = consumer_create(connection, mirror_consumer_config, mirror_stream_info)
msg = consumer_next(connection, consumer_info)
@test msg isa NATS.Msg
@test msg.subject == "SOME_STREAM.foo"
stream_delete(connection, stream_info)
stream_delete(connection, mirror_stream_info)
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 388 | bytes = UInt8[0x4d, 0x53, 0x47, 0x20, 0x61, 0x61, 0x61, 0x20, 0x78, 0x58, 0x6a, 0x76, 0x78, 0x4a, 0x76, 0x54, 0x76, 0x47, 0x44, 0x42, 0x6d, 0x6a, 0x58, 0x63, 0x32, 0x4f, 0x75, 0x45, 0x20, 0x30, 0x0d, 0x0a, 0x0d, 0x0a]
b = repeat(bytes, 1000000)
io = IOBuffer(b)
function bench_read(io::IO)
cnt = 0
@time NATS.read_messages(io) do msg
cnt += 1
end
@info cnt
end | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 2969 |
msg = "MSG foo 84s6LXpSRziIFL4w5Spm 16\r\n1111111111111111\r\n"
io = IOBuffer(repeat(msg, 10000))
@time for b in readavailable(io)
end
using NATS
res = NATS.parser_loop(io) do res
@info length(res)
end
function bench_parser()
msg = "MSG foo 84s6LX 16\r\n1111111111111111\r\n"
io = IOBuffer(repeat(msg, 1000000))
s = 0
ret = []
@time NATS.parser_loop(io) do res
ret = res
@info "res" first(res) length(res)
end
ret
end
function bench_parser_replyto()
msg = "MSG foo 84s6LXpSRziIFL4w5Spm asdf 16\r\n1111111111111111\r\n"
io = IOBuffer(repeat(msg, 1000000))
s = 0
ret = []
@time NATS.parser_loop(io) do res
ret = res
@info "res" first(res) length(res)
end
ret
end
function bench_parser_headers()
msg = "HMSG FOO.BAR 9 34 45\r\nNATS/1.0\r\nFoodGroup: vegetable\r\n\r\nHello World\r\n"
io = IOBuffer(repeat(msg, 1000000))
s = 0
@time NATS.parser_loop(io) do res
@info "res" first(res) length(res)
end
end
function bench_parser_headers_replyto()
msg = "HMSG FOO.BAR 9 asdf 34 45\r\nNATS/1.0\r\nFoodGroup: vegetable\r\n\r\nHello World\r\n"
io = IOBuffer(repeat(msg, 1000000))
s = 0
ret = []
@time NATS.parser_loop(io) do res
ret = res
@info "res" first(res) length(res)
end
ret
end
function bench()
msg = "MSG foo 84s6LXpSRziIFL4w5Spm 16\r\n1111111111111111\r\n"
io = IOBuffer(repeat(msg, 1000000))
s = 0
@time for b in readavailable(io)
if s < 10000
if b == 0x44
s += 2
elseif b == 0x45
s += 5
elseif b == 0x48
s -= 1
elseif b == 0x49
s += 9
elseif b == 0x40
s -= 5
end
else
s+= 100
end
end
end
using StringViews
function scan()
msg = "MSG foo 84s6LXpSRziIFL4w5Spm 16\r\n1111111111111111\r\n"
io = IOBuffer(repeat(msg, 1000000))
s = 0
m = false
cr = false
crlf = false
in_payload = false
pos = 0
ends = sizehint!(Int64[], 2000000)
subs = sizehint!(AbstractString[], 2000000)
@time buffer = readavailable(io)
msgs = []
last_end = 0
@time for b in buffer
pos += 1
crlf = false
if b == convert(UInt8, '\r')
cr = true
elseif cr && b == convert(UInt8, '\n')
crlf = true
cr = false
elseif b == convert(UInt8, 'M')
m = true
end
if !m && crlf
push!(msgs, NATS.Msg("foo", String(StringView(@view buffer[last_end+1:pos])), "", 16, "1111111111111111"))
# push!(msgs, SubString(StringView(@view buffer[last_end+1:pos]), 9, 29))
# push!(msgs, SubString(StringView(@view buffer[last_end+1:pos]), 9, 29))
last_end = pos
elseif crlf
m = false
end
end
msgs
end | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 9942 | @testset "Parsing server operations." begin
unpack(msgs) = map(msgs) do msg; msg isa NATS.MsgRaw ? convert(NATS.Msg, msg) : msg end
expected = [
NATS.Info("NCUWF4KWI6NQR4NRT2ZWBI6WBW6V63XERJGREROVAVV6WZ4O4D7R6CVK", "my_nats_server", "2.9.21", "go1.19.12", "0.0.0.0", 4222, true, 1048576, 1, 0x000000000000003d, nothing, nothing, nothing, nothing, nothing, nothing, nothing, "b2e7725", true, nothing, "127.0.0.1", nothing, nothing, nothing),
NATS.Msg("FOO.BAR", 9, nothing, 0, uint8_vec("Hello World")),
NATS.Msg("FOO.BAR", 9, "GREETING.34", 0, uint8_vec("Hello World")),
NATS.Msg("FOO.BAR", 9, nothing, 34, uint8_vec("NATS/1.0\r\nFoodGroup: vegetable\r\n\r\nHello World")),
NATS.Msg("FOO.BAR", 9, "BAZ.69", 34, uint8_vec("NATS/1.0\r\nFoodGroup: vegetable\r\n\r\nHello World")),
NATS.Msg("FOO.BAR", 9, nothing, 16, uint8_vec("NATS/1.0 503\r\n\r\n")),
NATS.Ping(),
NATS.Pong(),
NATS.Ok(),
NATS.Err("Unknown Protocol Operation"),
NATS.Msg("FOO.BAR", 9, nothing, 0, uint8_vec("Hello World")),
]
# Basic protocol parsing
data_to_parse = UInt8[]
append!(data_to_parse, """INFO {"server_id":"NCUWF4KWI6NQR4NRT2ZWBI6WBW6V63XERJGREROVAVV6WZ4O4D7R6CVK","server_name":"my_nats_server","version":"2.9.21","proto":1,"git_commit":"b2e7725","go":"go1.19.12","host":"0.0.0.0","port":4222,"headers":true,"max_payload":1048576,"jetstream":true,"client_id":61,"client_ip":"127.0.0.1"} \r\n""")
append!(data_to_parse, "MSG FOO.BAR 9 11\r\nHello World\r\n")
append!(data_to_parse, "MSG FOO.BAR 9 GREETING.34 11\r\nHello World\r\n")
append!(data_to_parse, "HMSG FOO.BAR 9 34 45\r\nNATS/1.0\r\nFoodGroup: vegetable\r\n\r\nHello World\r\n")
append!(data_to_parse, "HMSG FOO.BAR 9 BAZ.69 34 45\r\nNATS/1.0\r\nFoodGroup: vegetable\r\n\r\nHello World\r\n")
append!(data_to_parse, "HMSG FOO.BAR 9 16 16\r\nNATS/1.0 503\r\n\r\n\r\n")
append!(data_to_parse, "PING\r\n")
append!(data_to_parse, "PONG\r\n")
append!(data_to_parse, "+OK\r\n")
append!(data_to_parse, "-ERR 'Unknown Protocol Operation'\r\n")
append!(data_to_parse, "MSG FOO.BAR 9 11\r\nHello World\r\n")
io = IOBuffer(data_to_parse)
result = NATS.ProtocolMessage[]
NATS.parser_loop(io) do msgs
append!(result, unpack(msgs))
end
@test result == expected
# Test case insensivity of protocol parser.
data_to_parse = UInt8[]
append!(data_to_parse, """info {"server_id":"NCUWF4KWI6NQR4NRT2ZWBI6WBW6V63XERJGREROVAVV6WZ4O4D7R6CVK","server_name":"my_nats_server","version":"2.9.21","proto":1,"git_commit":"b2e7725","go":"go1.19.12","host":"0.0.0.0","port":4222,"headers":true,"max_payload":1048576,"jetstream":true,"client_id":61,"client_ip":"127.0.0.1"} \r\n""")
append!(data_to_parse, "msg FOO.BAR 9 11\r\nHello World\r\n")
append!(data_to_parse, "msg FOO.BAR 9 GREETING.34 11\r\nHello World\r\n")
append!(data_to_parse, "hmsg FOO.BAR 9 34 45\r\nNATS/1.0\r\nFoodGroup: vegetable\r\n\r\nHello World\r\n")
append!(data_to_parse, "hmsg FOO.BAR 9 BAZ.69 34 45\r\nNATS/1.0\r\nFoodGroup: vegetable\r\n\r\nHello World\r\n")
append!(data_to_parse, "hmsg FOO.BAR 9 16 16\r\nNATS/1.0 503\r\n\r\n\r\n")
append!(data_to_parse, "ping\r\n")
append!(data_to_parse, "pong\r\n")
append!(data_to_parse, "+ok\r\n")
append!(data_to_parse, "-err 'Unknown Protocol Operation'\r\n")
append!(data_to_parse, "msg FOO.BAR 9 11\r\nHello World\r\n")
io = IOBuffer(data_to_parse)
result = NATS.ProtocolMessage[]
NATS.parser_loop(io) do msgs
append!(result, unpack(msgs))
end
@test result == expected
# Test multiple whitespaces parsing.
data_to_parse = UInt8[]
append!(data_to_parse, """INFO {"server_id":"NCUWF4KWI6NQR4NRT2ZWBI6WBW6V63XERJGREROVAVV6WZ4O4D7R6CVK","server_name":"my_nats_server","version":"2.9.21","proto":1,"git_commit":"b2e7725","go":"go1.19.12","host":"0.0.0.0","port":4222,"headers":true,"max_payload":1048576,"jetstream":true,"client_id":61,"client_ip":"127.0.0.1"} \r\n""")
append!(data_to_parse, "MSG\tFOO.BAR\t9\t11\r\nHello World\r\n")
append!(data_to_parse, "MSG FOO.BAR 9 GREETING.34 11\r\nHello World\r\n")
append!(data_to_parse, "HMSG \t FOO.BAR\t \t9\t \t34 \t \t 45\r\nNATS/1.0\r\nFoodGroup: vegetable\r\n\r\nHello World\r\n")
append!(data_to_parse, "HMSG\t FOO.BAR\t 9\t BAZ.69\t 34\t 45\r\nNATS/1.0\r\nFoodGroup: vegetable\r\n\r\nHello World\r\n")
append!(data_to_parse, "HMSG \tFOO.BAR \t9 \t16 \t16\r\nNATS/1.0 503\r\n\r\n\r\n")
append!(data_to_parse, "PING\r\n")
append!(data_to_parse, "PONG\r\n")
append!(data_to_parse, "+OK\r\n")
append!(data_to_parse, "-ERR 'Unknown Protocol Operation'\r\n")
append!(data_to_parse, "MSG FOO.BAR 9 11\r\nHello World\r\n")
io = IOBuffer(data_to_parse)
result = NATS.ProtocolMessage[]
NATS.parser_loop(io) do msgs
append!(result, unpack(msgs))
end
@test result == expected
# Test malformed messages.
io = IOBuffer("this is not expected\r\n")
@test_throws ErrorException NATS.parser_loop(io) do; end
io = IOBuffer("MSG FOO.BAR 9 test 11 11\r\nToo long payload\r\n")
@test_throws ErrorException NATS.parser_loop(io) do; end
end
@testset "Serializing client operations." begin
serialize(m) = String(repr(NATS.MIME_PROTOCOL(), m))
json = """{"verbose":false,"pedantic":false,"tls_required":false,"lang":"julia","version":"0.0.1"}"""
@test serialize(JSON3.read(json, NATS.Connect)) == """CONNECT $json\r\n"""
@test serialize(Pub("FOO", nothing, 0, uint8_vec("Hello NATS!"))) == "PUB FOO 11\r\nHello NATS!\r\n"
@test serialize(Pub("FRONT.DOOR", "JOKE.22", 0, uint8_vec("Knock Knock"))) == "PUB FRONT.DOOR JOKE.22 11\r\nKnock Knock\r\n"
@test serialize(Pub("NOTIFY", nothing, 0, UInt8[])) == "PUB NOTIFY 0\r\n\r\n"
@test serialize(Pub("FOO", nothing, 22, uint8_vec("NATS/1.0\r\nBar: Baz\r\n\r\nHello NATS!"))) == "HPUB FOO 22 33\r\nNATS/1.0\r\nBar: Baz\r\n\r\nHello NATS!\r\n"
@test serialize(Pub("FRONT.DOOR", "JOKE.22", 45, uint8_vec("NATS/1.0\r\nBREAKFAST: donut\r\nLUNCH: burger\r\n\r\nKnock Knock"))) == "HPUB FRONT.DOOR JOKE.22 45 56\r\nNATS/1.0\r\nBREAKFAST: donut\r\nLUNCH: burger\r\n\r\nKnock Knock\r\n"
@test serialize(Pub("NOTIFY", nothing, 22, uint8_vec("NATS/1.0\r\nBar: Baz\r\n\r\n"))) == "HPUB NOTIFY 22 22\r\nNATS/1.0\r\nBar: Baz\r\n\r\n\r\n"
@test serialize(Pub("MORNING.MENU", nothing, 47, uint8_vec("NATS/1.0\r\nBREAKFAST: donut\r\nBREAKFAST: eggs\r\n\r\nYum!"))) == "HPUB MORNING.MENU 47 51\r\nNATS/1.0\r\nBREAKFAST: donut\r\nBREAKFAST: eggs\r\n\r\nYum!\r\n"
@test serialize(Sub("FOO", nothing, 1)) == "SUB FOO 1\r\n"
@test serialize(Sub("BAR", "G1", 44)) == "SUB BAR G1 44\r\n"
@test serialize(Unsub(1, nothing)) == "UNSUB 1\r\n"
@test serialize(Unsub(1, 5)) == "UNSUB 1 5\r\n"
end
@testset "Serializing headers." begin
msg = Msg("FOO.BAR", 9, "BAZ.69", 30, uint8_vec("NATS/1.0\r\nA: B\r\nC: D\r\nC: E\r\n\r\nHello World"))
@test headers(msg) == ["A" => "B", "C" => "D", "C" => "E"]
@test headers(msg, "C") == ["D", "E"]
@test_throws ArgumentError header(msg, "C")
@test header(msg, "A") == "B"
@test String(repr(MIME_HEADERS(), headers(msg))) == String(msg.payload[begin:msg.headers_length])
@test isempty(headers(Msg("FOO.BAR", 9, "GREETING.34", 0, uint8_vec("Hello World"))))
no_responder_msg = Msg("FOO.BAR", 9, "BAZ.69", 16, uint8_vec("NATS/1.0 503\r\n\r\n"))
@test NATS.statuscode(no_responder_msg) == 503
end
@testset "Serializing typed handler results" begin
@test String(repr(MIME_PAYLOAD(), "Hi!")) == "Hi!"
@test String(repr(MIME_PAYLOAD(), ("Hi!", Headers()))) == "Hi!"
@test String(repr(MIME_PAYLOAD(), (nothing, Headers()))) == ""
@test String(repr(MIME_PAYLOAD(), Headers())) == ""
@test String(repr(MIME_PAYLOAD(), (nothing, nothing))) == ""
@test String(repr(MIME_HEADERS(), "Hi!")) == ""
@test String(repr(MIME_HEADERS(), ("Hi!", Headers()))) == "NATS/1.0\r\n\r\n"
@test String(repr(MIME_HEADERS(), ("Hi!", nothing))) == ""
@test String(repr(MIME_HEADERS(), (nothing, Headers()))) == "NATS/1.0\r\n\r\n"
@test String(repr(MIME_HEADERS(), Headers())) == "NATS/1.0\r\n\r\n"
@test String(repr(MIME_HEADERS(), ["A" => "B"])) == "NATS/1.0\r\nA: B\r\n\r\n"
@test String(repr(MIME_HEADERS(), (nothing, nothing))) == ""
end
@testset "Nonce signatures" begin
seed = "SUAJ4LZRG3KF7C7U4E5737YMAOGUAWBODUM6DBWLY4UPUMXH6TH7JLQFDM"
nkey = "UAGPV4UFVS34M2XGY7HLSNEBDVJZZDZ6XMQ4NTXVEMKZQNSFH2AJFUA5"
nonce = "XTdilcu9paonaBQ"
sig = "3tsErI9fNKHWOHLAbc_XQ8Oo3XHv__7I_fA1aQ7xod3gYpxhDzt1vItbQLv3FhDtDFycxJJ0wA26rG3NEwWZBg"
@test NATS.sign(nonce, seed) == sig
seed = "SUADPKZWX3XJQO4GJEX2IGZAKCYUSLSLNJXFG7KPAYAODEVABRK6ZKKALA"
nkey= "UDBKUC5JFUX5SDF6CGBT3WAZEZSJTGMWWSCRJMODEUPVOKBPCLVODH2J"
nonce = "HiA_hND1AV-DjmM"
sig = "g4HDazX_ZZig_FOFBzhorLSYCEDRlv20Y5vErFjDlTRZMqaaF27ImP16es_GI83Fn59xr9V98Ux5GlEvvaeADQ"
@test NATS.sign(nonce, seed) == sig
end
@testset "Plain text messages" begin
msg = NATS.Msg("FOO.BAR", 9, "some_inbox", 34, uint8_vec("NATS/1.0\r\nFoodGroup: vegetable\r\n\r\nHello World"))
msg_text = repr(MIME("text/plain"), msg)
@test msg_text == "HMSG FOO.BAR 9 some_inbox 34 45\r\nNATS/1.0\r\nFoodGroup: vegetable\r\n\r\nHello World"
msg = NATS.Msg("FOO.BAR", 9, "some_inbox", 34, uint8_vec("NATS/1.0\r\nFoodGroup: vegetable\r\n\r\n$(repeat("X", 1000))"))
msg_text = repr(MIME("text/plain"), msg)
@test msg_text == "HMSG FOO.BAR 9 some_inbox 34 1034\r\nNATS/1.0\r\nFoodGroup: vegetable\r\n\r\n$(repeat("X", 466)) ⋯ 534 bytes"
end
@testset "Subject validation" begin
pub = NATS.Pub("subject with space", nothing, 0, uint8_vec("Hello NATS!"))
@test_throws "Publication subject contains invalid character ' '" NATS.validate(pub)
end | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 4891 |
using Test
using NATS
using Random
using JSON3
@testset "Publish subscribe" begin
c = Channel()
sub = subscribe(nc, "SOME.BAR") do msg
put!(c, msg)
end
publish(nc, "SOME.BAR", "Hi!")
result = take!(c)
@test result isa NATS.Msg
@test payload(result) == "Hi!"
@test length(nc.sub_data) == 1
drain(nc, sub)
@test length(nc.sub_data) == 0
end
NATS.status()
@testset "Publish subscribe with sync handlers" begin
connection = NATS.connect()
c = Channel()
sub = subscribe(connection, "SOME.BAR") do msg
put!(c, msg)
end
publish(connection, "SOME.BAR", "Hi!")
result = take!(c)
@test result isa NATS.Msg
@test payload(result) == "Hi!"
@test length(connection.sub_data) == 1
drain(connection, sub)
@test length(connection.sub_data) == 0
c = Channel()
sub = subscribe(connection, "SOME.BAR") do msg::String
put!(c, msg)
end
publish(connection, "SOME.BAR", "Hi!")
result = take!(c)
drain(connection, sub)
@test result == "Hi!"
end
NATS.status()
@testset "Typed subscription handlers" begin
c = Channel()
sub = subscribe(nc, "SOME.BAR") do msg::String
put!(c, msg)
end
publish(nc, "SOME.BAR", "Hi!")
result = take!(c)
@test result == "Hi!"
@test length(nc.sub_data) == 1
drain(nc, sub)
@test length(nc.sub_data) == 0
end
NATS.status()
@testset "Publish subscribe with headers" begin
c = Channel()
sub = subscribe(nc, "SOME.BAR") do msg
put!(c, msg)
end
publish(nc, "SOME.BAR", ("Hi!", ["A" => "B"]))
result = take!(c)
@test result isa NATS.Msg
@test payload(result) == "Hi!"
@test headers(result) == ["A" => "B"]
@test length(nc.sub_data) == 1
drain(nc, sub)
@test length(nc.sub_data) == 0
end
NATS.status()
@testset "Subscription without argument" begin
subject = randstring(8)
was_delivered = false
sub = subscribe(nc, subject) do
was_delivered = true
"nothing to do"
end
publish(nc, subject, "Hi!")
drain(nc, sub)
@test was_delivered
end
NATS.status()
@testset "Subscription with multiple arguments" begin
subject = randstring(8)
# TODO: test if error message is clear.
@test_throws ErrorException subscribe(nc, subject) do x, y, z
"nothing to do"
end
end
@testset "Synchronous subscriptions" begin
subject = randstring(8)
sub = subscribe(nc, subject)
msg = next(nc, sub; no_wait = true)
@test isnothing(msg)
@async begin
for i in 1:100
sleep(0.01)
publish(nc, subject, """{"x": 1}""")
end
sleep(0.2)
unsubscribe(nc, sub)
end
msg = next(nc, sub)
@test msg isa NATS.Msg
json = next(JSON3.Object, nc, sub)
@test json.x == 1
msgs = next(nc, sub, 10)
@test msgs isa Vector{NATS.Msg}
@test length(msgs) == 10
jsons = next(JSON3.Object, nc, sub, 10)
@test length(jsons) == 10
sleep(2)
msgs = next(nc, sub, 78)
@test msgs isa Vector{NATS.Msg}
@test length(msgs) == 78
msgs = next(nc, sub, 100; no_wait = true, no_throw = true)
@test msgs isa Vector{NATS.Msg}
@test length(msgs) == 0
jsons = next(JSON3.Object, nc, sub, 100; no_throw = true, no_wait = true)
@test msgs isa Vector{NATS.Msg}
@test length(jsons) == 0
@test_throws "Client unsubscribed" next(nc, sub)
@test_throws "Client unsubscribed" next(JSON3.Object, nc, sub)
@test_throws "Client unsubscribed" next(nc, sub; no_wait = true)
@test_throws "Client unsubscribed" next(JSON3.Object, nc, sub)
@test_throws "Client unsubscribed" next(nc, sub, 2)
@test_throws "Client unsubscribed" next(JSON3.Object, nc, sub, 2)
@test isnothing(next(nc, sub; no_throw = true, no_wait = true))
end
@testset "10k subscriptions" begin
n_subs = 10000
n_pubs = 10
subject = randstring(8)
subject_ack = randstring(8)
ch = Channel(Inf)
sub_nc = NATS.connect()
for i in 1:n_subs
subscribe(sub_nc, subject) do msg
put!(ch, msg)
publish(sub_nc, subject_ack, "ack")
end
end
sleep(1)
pub_nc = NATS.connect()
ack_count = Threads.Atomic{Int64}(0)
subscribe(pub_nc, subject_ack) do msg
Threads.atomic_add!(ack_count, 1)
end
sleep(1)
for i in 1:n_pubs
publish(pub_nc, subject, "Test 10k subs: msg $i.")
end
sleep(3)
drain(sub_nc)
drain(pub_nc)
sub_stats = NATS.stats(sub_nc)
pub_stats = NATS.stats(pub_nc)
@test ack_count.value == n_pubs * n_subs
@test Base.n_avail(ch) == n_pubs * n_subs
@test sub_stats.msgs_handled == n_pubs * n_subs
@test sub_stats.msgs_published == n_pubs * n_subs
@test pub_stats.msgs_handled == n_pubs * n_subs
@test pub_stats.msgs_published == n_pubs
end
NATS.status()
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 4078 | using Test
using NATS
using Random
using JSON3
@testset "Request reply" begin
sub = reply(nc, "SOME.REQUESTS") do msg
"This is a reply."
end
result, tm = @timed request(nc, "SOME.REQUESTS")
@info "First reply time was $(1000 * tm) ms."
result, tm = @timed request(nc, "SOME.REQUESTS")
@info "Second reply time was $(1000 * tm) ms."
drain(nc, sub)
@test result isa NATS.Msg
@test payload(result) == "This is a reply."
end
NATS.status()
@testset "Request multiple replies." begin
subject = randstring(10)
sub1 = reply(nc, subject) do msg
"Reply from service 1."
end
sub2 = reply(nc, subject) do msg
"Reply from service 2."
end
results = request(nc, 2, subject, "This is request payload")
drain(nc, sub1)
drain(nc, sub2)
@test length(results) == 2
payloads = payload.(results)
@test "Reply from service 1." in payloads
@test "Reply from service 2." in payloads
end
NATS.status()
@testset "4K requests" begin
n = 4000
subject = @lock NATS.state.lock randstring(5)
sub = reply(nc, subject) do msg
"This is a reply."
end
results = Channel(n)
cond = Channel()
for _ in 1:n
t = Threads.@spawn :default begin
msg = if haskey(ENV, "CI")
request(nc, subject; timer=Timer(20))
else
request(nc, subject)
end
put!(results, msg)
if Base.n_avail(results) == n
close(cond)
close(results)
end
end
errormonitor(t)
end
@async begin sleep(40); close(cond); close(results) end
if !haskey(ENV, "CI")
@async interactive_status(cond)
end
try take!(cond) catch end
unsubscribe(nc, sub)
replies = collect(results)
@test length(replies) == n
@test all(r -> payload(r) == "This is a reply.", replies)
NATS.status()
end
NATS.status()
@testset "4K requests external" begin
try
request(nc, "help.please")
catch
@info "Skipping \"4K requests external\" testset. Ensure `nats reply help.please 'OK, I CAN HELP!!!'` is running."
return
end
n = 4000
results = Channel(n)
cond = Channel()
t = @timed begin
for _ in 1:n
t = @async begin #TODO: add error monitor.
msg = request(nc, "help.please")
put!(results, msg)
if Base.n_avail(results) == n
close(cond)
close(results)
end
end
end
@async begin sleep(30); close(cond); close(results) end
try take!(cond) catch end
replies = collect(results)
end
replies = t.value
@test length(replies) == n
@test all(r -> payload(r) == "OK, I CAN HELP!!!", replies)
@info "Total time of $n requests is $(t.time) s, average $(1000 * t.time / n) ms per request."
end
NATS.status()
@testset "No responders." begin
@test_throws NATSError request(nc, "SOME.NULL")
end
NATS.status()
@testset "Typed request reply tests" begin
sub = reply(nc, "SOME.REQUESTS") do msg::String
"Received $msg"
end
result = request(String, nc, "SOME.REQUESTS", "Hi!")
drain(nc, sub)
@test result isa String
@test result == "Received Hi!"
sub = reply(nc, "SOME.REQUESTS") do msg::JSON3.Object
word = msg[:message]
JSON3.read("""{"reply": "This is a reply for '$word'"}""")
end
result = request(JSON3.Object, nc, "SOME.REQUESTS", JSON3.read("""{"message": "Hi!"}"""))
drain(nc, sub)
@test result[:reply] == "This is a reply for 'Hi!'"
end
NATS.status()
@testset "Request reply with headers" begin
sub = reply(nc, "SOME.REQUESTS") do msg
"This is a reply.", ["A" => "B"]
end
result = request(nc, "SOME.REQUESTS")
drain(nc, sub)
@test result isa NATS.Msg
@test payload(result) == "This is a reply."
@test headers(result) == ["A" => "B"]
end
NATS.status()
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1537 | using NATS
using Test
using JSON3
using Sockets
using NATS: next_protocol_message
using NATS: Info, Msg, Ping, Pong, Ok, Err, Pub, Sub, Unsub, Connect
using NATS: Headers, headers, header
using NATS: MIME_PROTOCOL, MIME_PAYLOAD, MIME_HEADERS
include("util.jl")
@show Threads.nthreads()
@show Threads.nthreads(:interactive)
@show Threads.nthreads(:default)
include("protocol.jl")
function is_nats_available()
try
url = get(ENV, "NATS_CONNECT_URL", NATS.DEFAULT_CONNECT_URL)
host, port = NATS.host_port(url)
Sockets.getaddrinfo(host)
nc = NATS.connect()
sleep(5)
@assert nc.status == NATS.CONNECTED
@info "NATS avaliable, running connected tests."
true
catch err
@info "NATS unavailable, skipping connected tests." err
false
end
end
have_nats = is_nats_available()
@testset "Should run connected tests" begin
@test have_nats
end
if have_nats
include("connection.jl")
include("pubsub.jl")
include("reqreply.jl")
# include("channel.jl")
include("fallback_handler.jl")
include("experimental.jl")
@testset "All subs should be closed" begin
sleep(5)
for nc in NATS.state.connections
@test isempty(nc.sub_data)
@test isempty(nc.unsubs)
if nc.send_buffer.size > 0
@info "Buffer content" String(nc.send_buffer.data[begin:nc.send_buffer.size])
end
@test nc.send_buffer.size == 0
end
end
NATS.status()
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1496 |
using Test
using NATS
import Base: convert, show
struct Person
name::String
age::Int64
end
function convert(::Type{Person}, msg::NATS.Msg)
name, age = split(payload(msg), ",")
Person(name, parse(Int64, age))
end
function show(io::IO, ::NATS.MIME_PAYLOAD, person::Person)
print(io, person.name)
print(io, ",")
print(io, person.age)
end
nc = NATS.connect()
sleep(5)
@assert nc.status == NATS.CONNECTED "Cannot establish connection, ensure NATS is working on $(NATS.NATS_HOST):$(NATS.NATS_PORT)."
@testset "Publish subscribe with custom data" begin
c = Channel()
sub = subscribe(nc, "EMPLOYEES") do person::Person
put!(c, person)
end
publish(nc, "EMPLOYEES", Person("Jacek", 33))
result = take!(c)
@test result isa Person
@test result.name == "Jacek"
@test result.age == 33
@test length(nc.sub_data) == 1
drain(nc, sub)
@test length(nc.sub_data) == 0
end
@testset "Request reply with custom data" begin
sub = reply(nc, "EMPLOYEES.SUPERVISOR") do person::Person
if person.name == "Jacek"
Person("Zbigniew", 44), ["A" => "B"]
else
Person("Maciej", 55), ["A" => "B"]
end
end
supervisor = request(Person, nc, "EMPLOYEES.SUPERVISOR", Person("Jacek", 33))
@test supervisor isa Person
@test supervisor.name == "Zbigniew"
@test supervisor.age == 44
msg = request(nc, "EMPLOYEES.SUPERVISOR", Person("Anna", 33))
@test msg isa NATS.Msg
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1883 |
using Test
using NATS
import Base: convert, show
struct Person
name::String
age::Int64
departament::String
end
function convert(::Type{Person}, msg::NATS.Msg)
name, age, departament = split(payload(msg), ",")
Person(name, parse(Int64, age), departament)
end
function show(io::IO, ::NATS.MIME_PAYLOAD, person::Person)
print(io, person.name)
print(io, ",")
print(io, person.age)
print(io, ",")
print(io, person.departament)
end
nc = NATS.connect()
sleep(5)
@assert nc.status == NATS.CONNECTED "Cannot establish connection."
@testset "Publish subscribe with custom data" begin
c = Channel()
sub = subscribe(nc, "EMPLOYEES") do person::Person
put!(c, person)
end
publish(nc, "EMPLOYEES", Person("Jacek", 33, "IT"))
result = take!(c)
@test result isa Person
@test result.name == "Jacek"
@test result.age == 33
@test length(nc.sub_data) == 1
drain(nc, sub)
@test length(nc.sub_data) == 0
end
@testset "Request reply with custom data" begin
sub = reply(nc, "EMPLOYEES.SUPERVISOR") do person::Person
if person.departament == "IT"
Person("Zbigniew", 44, "IT"), ["status" => "ok"]
elseif person.departament == "HR"
Person("Maciej", 55, "HR"), ["status" => "ok"]
else
@info "Error response."
["status" => "error", "message" => "Unexpected departament `$(person.departament)`"]
end
end
supervisor = request(Person, nc, "EMPLOYEES.SUPERVISOR", Person("Jacek", 33, "IT"))
@test supervisor isa Person
@test supervisor.name == "Zbigniew"
@test supervisor.age == 44
msg = request(nc, "EMPLOYEES.SUPERVISOR", Person("Anna", 33, "ACCOUNTING"))
@test msg isa NATS.Msg
@test headers(msg) == ["status" => "error", "message" => "Unexpected departament `ACCOUNTING`"]
drain(nc, sub)
end | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1422 | using NATS
using Random
@show getpid()
Base.exit_on_sigint(false)
function sigint_current_process()
cmd = `kill -2 $(getpid())`
res = run(cmd)
res.exitcode == 0 || error("$cmd failed with $(res.exitcode)")
end
function run_test()
connection = NATS.connect()
received_count = Threads.Atomic{Int64}(0)
published_count = Threads.Atomic{Int64}(0)
subject = "pub_subject"
sub = subscribe(connection, subject) do msg
Threads.atomic_add!(received_count, 1)
end
sleep(0.5)
pub_task = Threads.@spawn disable_sigint() do
Base.sigatomic_begin()
for i in 1:1000
timer = Timer(0.01)
for _ in 1:10
publish(connection, subject, "Hi!")
end
Threads.atomic_add!(published_count, 10)
try wait(timer) catch end
end
@info "Publisher finished."
end
# errormonitor(pub_task)
sleep(2)
@info "Published: $(published_count.value), received: $(received_count.value)."
sleep(2)
end
t = Threads.@spawn :default disable_sigint() do
Base.sigatomic_begin()
run_test()
end
errormonitor(t)
try
while true
sleep(0.2)
end
catch err
@error err
end
drain(NATS.connection(1))
NATS.status()
if NATS.status(NATS.connection(1)) == NATS.DRAINED
@info "Test passed correctly."
else
@error "Test failed, connection status is not DRAINED"
end
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 163 | using NATS
using Random
Base.exit_on_sigint(false)
t = Threads.@spawn :default NATS.start_interrupt_handler()
wait(t)
NATS.start_interrupt_handler(true)
sleep(5)
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 1428 | using NATS
using Random
Base.exit_on_sigint(false)
@show isinteractive()
function sigint_current_process()
cmd = `kill -2 $(getpid())`
res = run(cmd)
res.exitcode == 0 || error("$cmd failed with $(res.exitcode)")
end
function run_test()
connection = NATS.connect()
received_count = Threads.Atomic{Int64}(0)
published_count = Threads.Atomic{Int64}(0)
subject = "pub_subject"
sub = subscribe(connection, subject) do msg
Threads.atomic_add!(received_count, 1)
end
sleep(0.5)
pub_task = Threads.@spawn begin
for i in 1:10000
timer = Timer(0.001)
for _ in 1:10
publish(connection, subject, "Hi!")
end
Threads.atomic_add!(published_count, 10)
try wait(timer) catch end
end
@info "Publisher finished."
end
sleep(2)
@info "Published: $(published_count.value), received: $(received_count.value)."
@info "Sending SIGINT"
@async begin
sleep(2)
sigint_current_process()
end
try wait(pub_task) catch end
@info "Published: $(published_count.value), received: $(received_count.value)."
sleep(2)
end
t = Threads.@spawn :default run_test()
wait(t)
sleep(5)
NATS.status()
if NATS.status(NATS.connection(1)) == NATS.DRAINED
@info "Test passed correctly."
else
@error "Test failed, connection status is not DRAINED"
end
exit() | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | code | 513 | function interactive_status(cond = nothing)
try
while true
NATS.status()
sleep(0.05)
if !isnothing(cond) && !isopen(cond)
return
end
write(stdout, "\u1b[A\u1b[A\u1b[A\u1b[A\u1b[A\u1b[A\u1b[A\u1b[K\u1b[K\u1b[K\u1b[K\u1b[K\u1b[K\u1b[K\u1b[K\u1b[K\u1b[K\u1b[K\u1b[K")
end
catch e
if !(e isa InterruptException)
throw(e)
end
end
end
uint8_vec(s::String) = convert.(UInt8, collect(s))
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 3228 |
# NATS client for Julia.
[](https://github.com/jakubwro/NATS.jl/actions/workflows/runtests.yml)
[](https://github.com/jakubwro/NATS.jl/actions/workflows/chaos.yml)
[](https://github.com/jakubwro/NATS.jl/actions/workflows/benchmarks.yml)
[](https://github.com/jakubwro/NATS.jl/actions/workflows/tls.yaml)
[](https://github.com/jakubwro/NATS.jl/actions/workflows/auth.yaml)
[](https://github.com/jakubwro/NATS.jl/actions/workflows/cluster.yaml)
[](https://github.com/jakubwro/NATS.jl/actions/workflows/jetstream.yaml)
[](https://github.com/jakubwro/NATS.jl/actions/workflows/documentation.yml)
[](https://codecov.io/gh/jakubwro/NATS.jl)
[](https://jakubwro.github.io/NATS.jl/dev)
## Description
[NATS](https://nats.io) client for Julia.
This client is feature complete in terms of `Core NATS` protocol and most of [JetStream](https://docs.nats.io/nats-concepts/jetstream) API.
- [x] All `NATS` authentication methods
- [x] TLS support
- [x] Zero copy protocol parser
Performance is matching reference `go` implementation.
## Compatibility
### Julia
It was tested in `julia` `1.9` and `1.10`
### NATS
It was tested on `NATS` `2.10`.
## Quick examples
Start nats-server:
```
docker run -p 4222:4222 nats:latest
```
### Publish subscribe
```julia
julia> using NATS
julia> nc = NATS.connect()
NATS.Connection(my_cluster cluster, CONNECTED, 0 subs, 0 unsubs)
julia> sub = subscribe(nc, "test_subject") do msg
@show payload(msg)
end;
julia> publish(nc, "test_subject", "Hello.")
payload(msg) = "Hello."
julia> drain(nc, sub)
```
## Request reply
### Connecting to external service
```bash
> nats reply help.please 'OK, I CAN HELP!!!'
20:35:19 Listening on "help.please" in group "NATS-RPLY-22"
```
```julia
julia> using NATS
julia> nc = NATS.connect()
NATS.Connection(my_cluster cluster, CONNECTED, 0 subs, 0 unsubs)
julia> rep = @time NATS.request(nc, "help.please");
0.003854 seconds (177 allocations: 76.359 KiB)
julia> payload(rep)
"OK, I CAN HELP!!!"
```
### Reply to requests from julia
```julia
julia> using NATS
julia> nc = NATS.connect()
NATS.Connection(my_cluster cluster, CONNECTED, 0 subs, 0 unsubs)
julia> sub = reply(nc, "some.service") do msg
"This is response"
end
julia> rep = @time NATS.request(nc, "some.service");
0.002897 seconds (231 allocations: 143.078 KiB)
julia> payload(rep)
"This is response"
julia> drain(nc, sub)
```
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 8306 | # Benchmarks
Procedures to compare NATS.jl performance with `go` implementation.
Prerequisites:
- start nats-server
```
docker run -p 4222:4222 nats:latest
```
- enusre `nats` CLI tool is installed
## Request-Reply latency
### Native `go` latency
Start reply service
```
> nats reply foo "This is a reply" 2> /dev/null > /dev/null
```
Run benchmark with 1 publisher
```
> nats bench foo --pub 1 --request --msgs 1000
13:25:53 Benchmark in request-reply mode
13:25:53 Starting request-reply benchmark [subject=foo, multisubject=false, multisubjectmax=0, request=true, reply=false, msgs=1,000, msgsize=128 B, pubs=1, subs=0, pubsleep=0s, subsleep=0s]
13:25:53 Starting publisher, publishing 1,000 messages
Finished 0s [================] 100%
Pub stats: 1,676 msgs/sec ~ 209.57 KB/sec
```
Run benchmark with 10 publishers
```
> nats bench foo --pub 10 --request --msgs 10000
13:30:52 Benchmark in request-reply mode
13:30:52 Starting request-reply benchmark [subject=foo, multisubject=false, multisubjectmax=0, request=true, reply=false, msgs=10,000, msgsize=128 B, pubs=10, subs=0, pubsleep=0s, subsleep=0s]
13:30:52 Starting publisher, publishing 1,000 messages
13:30:52 Starting publisher, publishing 1,000 messages
13:30:52 Starting publisher, publishing 1,000 messages
13:30:52 Starting publisher, publishing 1,000 messages
13:30:52 Starting publisher, publishing 1,000 messages
13:30:52 Starting publisher, publishing 1,000 messages
13:30:52 Starting publisher, publishing 1,000 messages
13:30:52 Starting publisher, publishing 1,000 messages
13:30:52 Starting publisher, publishing 1,000 messages
13:30:52 Starting publisher, publishing 1,000 messages
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Pub stats: 11,522 msgs/sec ~ 1.41 MB/sec
[1] 1,158 msgs/sec ~ 144.85 KB/sec (1000 msgs)
[2] 1,158 msgs/sec ~ 144.84 KB/sec (1000 msgs)
[3] 1,158 msgs/sec ~ 144.79 KB/sec (1000 msgs)
[4] 1,157 msgs/sec ~ 144.73 KB/sec (1000 msgs)
[5] 1,157 msgs/sec ~ 144.68 KB/sec (1000 msgs)
[6] 1,156 msgs/sec ~ 144.62 KB/sec (1000 msgs)
[7] 1,154 msgs/sec ~ 144.36 KB/sec (1000 msgs)
[8] 1,153 msgs/sec ~ 144.22 KB/sec (1000 msgs)
[9] 1,153 msgs/sec ~ 144.13 KB/sec (1000 msgs)
[10] 1,152 msgs/sec ~ 144.03 KB/sec (1000 msgs)
min 1,152 | avg 1,155 | max 1,158 | stddev 2 msgs
```
### NATS.jl latency
Start reply service
```
julia> using NATS
julia> nc = NATS.connect();
julia> reply(nc, "foo") do
"This is a reply."
end
NATS.Sub("foo", nothing, "PDrH5FOxIgBpcnLO4xHD")
```
Run benchmark with 1 publisher:
```
> nats bench foo --pub 1 --request --msgs 1000
13:28:56 Benchmark in request-reply mode
13:28:56 Starting request-reply benchmark [subject=foo, multisubject=false, multisubjectmax=0, request=true, reply=false, msgs=1,000, msgsize=128 B, pubs=1, subs=0, pubsleep=0s, subsleep=0s]
13:28:56 Starting publisher, publishing 1,000 messages
Finished 0s [================] 100%
Pub stats: 1,565 msgs/sec ~ 195.64 KB/sec
```
Run benchmark with 10 publishers:
```
nats bench foo --pub 10 --request --msgs 10000
13:29:51 Benchmark in request-reply mode
13:29:51 Starting request-reply benchmark [subject=foo, multisubject=false, multisubjectmax=0, request=true, reply=false, msgs=10,000, msgsize=128 B, pubs=10, subs=0, pubsleep=0s, subsleep=0s]
13:29:51 Starting publisher, publishing 1,000 messages
13:29:51 Starting publisher, publishing 1,000 messages
13:29:51 Starting publisher, publishing 1,000 messages
13:29:51 Starting publisher, publishing 1,000 messages
13:29:51 Starting publisher, publishing 1,000 messages
13:29:51 Starting publisher, publishing 1,000 messages
13:29:51 Starting publisher, publishing 1,000 messages
13:29:51 Starting publisher, publishing 1,000 messages
13:29:51 Starting publisher, publishing 1,000 messages
13:29:51 Starting publisher, publishing 1,000 messages
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Finished 0s [================] 100%
Pub stats: 11,880 msgs/sec ~ 1.45 MB/sec
[1] 1,204 msgs/sec ~ 150.62 KB/sec (1000 msgs)
[2] 1,198 msgs/sec ~ 149.85 KB/sec (1000 msgs)
[3] 1,197 msgs/sec ~ 149.70 KB/sec (1000 msgs)
[4] 1,194 msgs/sec ~ 149.31 KB/sec (1000 msgs)
[5] 1,193 msgs/sec ~ 149.20 KB/sec (1000 msgs)
[6] 1,192 msgs/sec ~ 149.09 KB/sec (1000 msgs)
[7] 1,192 msgs/sec ~ 149.06 KB/sec (1000 msgs)
[8] 1,191 msgs/sec ~ 148.91 KB/sec (1000 msgs)
[9] 1,191 msgs/sec ~ 148.88 KB/sec (1000 msgs)
[10] 1,188 msgs/sec ~ 148.50 KB/sec (1000 msgs)
min 1,188 | avg 1,194 | max 1,204 | stddev 4 msgs
```
Results show 1,155 msgs/s for native go library and 1,194 msgs/s NATS.jl, we are good here.
## Publish-Subscribe benchmarks
### Run nats CLI benchmarks
```
> nats bench foo --pub 1 --sub 1 --size 16
13:43:05 Starting Core NATS pub/sub benchmark [subject=foo, multisubject=false, multisubjectmax=0, msgs=100,000, msgsize=16 B, pubs=1, subs=1, pubsleep=0s, subsleep=0s]
13:43:05 Starting subscriber, expecting 100,000 messages
13:43:05 Starting publisher, publishing 100,000 messages
Finished 0s [================] 100%
Finished 0s [================] 100%
NATS Pub/Sub stats: 2,251,521 msgs/sec ~ 34.36 MB/sec
Pub stats: 1,215,686 msgs/sec ~ 18.55 MB/sec
Sub stats: 1,154,802 msgs/sec ~ 17.62 MB/sec
```
### Benchmark NATS.jl publish
```
julia> using NATS
julia> nc = NATS.connect();
Threads.threadid() =
julia>
julia> Threads.threadid() = 1
Threads.threadid() = 1
julia>
julia> while true
for i in 1:100000
publish(nc, "foo", "This is a payload")
end
sleep(0.001)
end
```
```
> > nats bench foo --sub 1 --size 16
13:46:23 Starting Core NATS pub/sub benchmark [subject=foo, multisubject=false, multisubjectmax=0, msgs=100,000, msgsize=16 B, pubs=0, subs=1, pubsleep=0s, subsleep=0s]
13:46:23 Starting subscriber, expecting 100,000 messages
Finished 0s [================] 100%
Sub stats: 904,350 msgs/sec ~ 13.80 MB/sec
```
0.9M msgs vs 1.2M messages, I think all good here, received messages are buffered and async processed in separate task.
### Benchmark NATS.jl subscribe
Supress warnings
```julia
julia> using Logging
julia> Logging.LogLevel(Error)
Error
```
```julia
using NATS
nc = NATS.connect(send_buffer_limit = 1000000000)
function subscribe_until_timeout(nc::NATS.Connection, timeout = 1.0)
tm = Timer(timeout)
counter = 0
start = nothing
sub = subscribe(nc, "foo") do
if isnothing(start)
start = time()
end
counter += 1
end
wait(tm)
unsubscribe(nc, sub)
if counter == 0
@info "No messages"
else
@info "Processed $counter messages in $(time() - start) s. $(counter / (time() - start)) msgs/sec)"
end
counter
end
bench_task = @async begin
sub_task = Threads.@spawn :default subscribe_until_timeout(nc, 10.0)
Threads.@spawn :default while !istaskdone(sub_task)
publish(nc, "foo", "This is payload!")
end
wait(sub_task)
sub_task.result
end
_, tm = @timed wait(bench_task);
received_messages = bench_task.result
@info "$(received_messages / tm) msgs / sec"
```
```
```
Start publisher:
```
> nats bench foo --pub 1 --size 16 --msgs 20000000
13:50:56 Starting Core NATS pub/sub benchmark [subject=foo, multisubject=false, multisubjectmax=0, msgs=20,000,000, msgsize=16 B, pubs=1, subs=0, pubsleep=0s, subsleep=0s]
13:50:56 Starting publisher, publishing 20,000,000 messages
Publishing 3s [==========>-----] 68%
```
```julia
julia> subscribe_for_one_second()
[ Info: Processed 1680882 messages in 0.9680750370025635 s.
```
1,68M messages in NATS.jl vs 1.7M messages by go client.
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 5157 |
# Connection
## Connecting
```@docs
connect
```
## Reconnecting
Reconnect can be forced by user with `reconnect` function. This function can be also used
for reconnect a connection in `DISCONNECTED` state after reconnect retries were exhausted.
```@docs
reconnect
```
## Disconnecting
To gracefully close connection `drain` function is provided.
```@docs
drain(::NATS.Connection)
```
To use NATS it is needed to create connection handle with `connect` function. Connection creates asynchronous tasks to handle messages from server, sending published messages, monitor state of TCP connection and reconnect on network failure.
## Connection lifecycle
When `connect` is called it tries to initialize connection with NATS server. If
this process fails two things may happen depending on `retry_on_init_fail`
option:
1. Rethrow exception causing protocol initialization failure.
2. Return connection in state `CONNECTING` continuing reconnect process in background
Other wise connection in `CONNECTED` state is returned from `connect`.
In case of some critical failure like TCP connection closing or mallformed
protocol message conection will enter `CONNECTING` and try reconnect
according `reconnect_delays` specified. If it is unable to establish
connection with allowed retries connection will land in `DISCONNECTED`
state and only manual invocation of `reconnect` may restore it.
```@eval
using GraphViz
lifecycle = dot""" digraph G {
CONNECTING -> CONNECTED -> DRAINING -> DRAINED
CONNECTED -> CONNECTING [label="TCP failure", fontname="Courier New", fontsize=5, color="#aa0000", fontcolor="#aa0000"]
CONNECTING -> DISCONNECTED [label="reconnect\nretries\nexhausted", fontname="Courier New", fontsize=5, color="#aa0000", fontcolor="#aa0000"]
DISCONNECTED -> CONNECTING [label="reconnect()", fontname="Courier New", fontsize=5]
DISCONNECTED -> DRAINING [lable="unsubscribe and\nprocess messages"]
}"""
GraphViz.layout!(lifecycle, engine="dot")
open("lifecycle.svg", write = true) do f
GraphViz.render(f, lifecycle)
end
nothing
```

## Environment variables
There are several `ENV` variables defined to provide default parameters for `connect`. It is advised to rather define `ENV` variables and use parameter less invocation like `NATS.connect()` for better code portability.
| Parameter | `ENV` variable | Default value | Sent to server |
|--------------------|-------------------------|------------------|-----------------|
| `url` | `NATS_CONNECT_URL` | `localhost:4222` | no
| `verbose` | `NATS_VERBOSE` | `false` | yes
| `verbose` | `NATS_VERBOSE` | `false` | yes
| `pedantic` | `NATS_PEDANTIC` | `false` | yes
| `tls_required` | `NATS_TLS_REQUIRED` | `false` | yes
| `auth_token` | `NATS_AUTH_TOKEN` | | yes
| `user` | `NATS_USER` | | yes
| `pass` | `NATS_PASS` | | yes
| `jwt` | `NATS_JWT` | | yes
| `nkey` | `NATS_NKEY` | | yes
| `nkey_seed` | `NATS_NKEY_SEED` | | no
| `tls_ca_path` | `NATS_TLS_CA_PATH` | | no
| `tls_cert_path` | `NATS_TLS_CERT_PATH` | | no
| `tls_key_path` | `NATS_TLS_KEY_PATH` | | no
Additionally some parameters are provided to fine tune client for specific deployment setup.
| Parameter | `ENV` variable | Default value | Sent to server |
|-----------------------------|-------------------------------------|------------------|-----------------|
| `ping_interval` | `NATS_PING_INTERVAL_SECONDS` | `120` | no
| `max_pings_out` | `NATS_MAX_PINGS_OUT` | `2` | no
| `retry_on_init_fail` | `NATS_RETRY_ON_INIT_FAIL` | `false` | no
| `ignore_advertised_servers` | `NATS_IGNORE_ADVERTISED_SERVERS` | `false` | no
| `retain_servers_order` | `NATS_RETAIN_SERVERS_ORDER ` | `false` | no
| `drain_timeout` | `NATS_DRAIN_TIMEOUT_SECONDS` | `5.0` | no
| `drain_poll` | `NATS_DRAIN_POLL_INTERVAL_SECONDS` | `0.2` | no
| `send_buffer_limit` | `NATS_SEND_BUFFER_LIMIT_BYTES` | `2097152` | no
Reconnect `reconnect_delays` default `ExponentialBackOff` also can be configured from `ENV` variables. This is recommended to configure it with them rather than pass delays as argument.
| `ENV` variable | Default value |
|---------------------------------|----------------------|
| `NATS_RECONNECT_RETRIES` | `220752000000000000` |
| `NATS_RECONNECT_FIRST_DELAY` | `0.1` |
| `NATS_RECONNECT_MAX_DELAY` | `5.0` |
| `NATS_RECONNECT_FACTOR` | `5.0` |
| `NATS_RECONNECT_JITTER` | `0.1` |
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 3000 | # Transport data structures
## Using custom types as handler input
It is possible to use and return custom types inside subscription handlers if `convert` method from `NATS.Msg` is provided. See `src/protocol/convert.jl` for example implementation for `String`.
```@repl
using NATS
struct Person
name::String
age::Int64
end
import Base: convert
function convert(::Type{Person}, msg::NATS.Msg)
name, age = split(payload(msg), ",")
Person(name, parse(Int64, age))
end
connection = NATS.connect() # Important to create a connection after `convert` is defined
sub = subscribe(connection, "EMPLOYEES") do person::Person
@show person
end
publish(connection, "EMPLOYEES", "John,44")
sleep(0.2) # Wait for message delivered to sub
drain(connection, sub)
```
## Returning custom types from handler
It is also possible to return any type from a handler in `reply` and put any type as `publish` argument if conversion to `UTF-8` string is provided.
Note that both Julia and NATS protocol use `UTF-8` encoding, so no additional conversions are needed.
NATS module defines custom MIME types for payload and headers serialization:
```julia
const MIME_PAYLOAD = MIME"application/nats-payload"
const MIME_HEADERS = MIME"application/nats-headers"
```
Conversion method should look like this.
```@repl
using NATS
struct Person
name::String
age::Int64
end
import Base: convert, show
function convert(::Type{Person}, msg::NATS.Msg)
name, age = split(payload(msg), ",")
Person(name, parse(Int64, age))
end
function show(io::IO, ::NATS.MIME_PAYLOAD, person::Person)
print(io, person.name)
print(io, ",")
print(io, person.age)
end
connection = NATS.connect()
sub = reply(connection, "EMPLOYEES.SUPERVISOR") do person::Person
if person.name == "Alice"
Person("Bob", 44)
else
Person("Unknown", 0)
end
end
request(Person, connection, "EMPLOYEES.SUPERVISOR", Person("Alice", 22))
drain(connection, sub)
```
## Error handling
Errors can be handled with custom headers.
```@repl
using NATS
import Base: convert, show
struct Person
name::String
age::Int64
departament::String
end
function convert(::Type{Person}, msg::NATS.Msg)
name, age, departament = split(payload(msg), ",")
Person(name, parse(Int64, age), departament)
end
function show(io::IO, ::NATS.MIME_PAYLOAD, person::Person)
print(io, person.name)
print(io, ",")
print(io, person.age)
print(io, ",")
print(io, person.departament)
end
nc = NATS.connect()
sub = reply(nc, "EMPLOYEES.SUPERVISOR") do person::Person
if person.name == "Alice"
Person("Bob", 44, "IT"), ["status" => "ok"]
else
Person("Unknown", 0, ""), ["status" => "error", "message" => "Supervisor not defined for $(person.name)" ]
end
end
request(Person, nc, "EMPLOYEES.SUPERVISOR", Person("Alice", 33, "IT"))
error_response = request(nc, "EMPLOYEES.SUPERVISOR", Person("Anna", 33, "ACCOUNTING"));
headers(error_response)
drain(nc, sub)
```
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 996 | # Debugging
## Monitoring connection state
```@repl
using NATS
nc = NATS.connect()
@async NATS.status_change(nc) do state
@info "Connection to $(NATS.clustername(nc)) changed state to $state"
end
NATS.reconnect(nc)
NATS.drain(nc)
sleep(7) # Wait a moment to get DRAINED status as well
```
## Connection and subscription statistics
There are detailed statistics of published and received messages collected.
They can be accessed for each subscription and connection. Connection statistics
aggregates stats for all its subscriptions.
```@repl
using NATS
nc = NATS.connect()
sub1 = subscribe(nc, "topic") do msg
t = Threads.@spawn publish(nc, "other_topic", payload(msg))
wait(t)
end
sub2 = subscribe(nc, "other_topic") do msg
@show payload(msg)
end
NATS.stats(nc)
publish(nc, "topic", "Hi!")
NATS.stats(nc)
NATS.stats(nc, sub1)
NATS.stats(nc, sub2)
sleep(0.1) # Wait for message to be propagated
NATS.stats(nc)
NATS.stats(nc, sub1)
NATS.stats(nc, sub2)
NATS.drain(nc)
```
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 1894 |
# Design notes
## Parsing
Benchmark after any changes to parsing, "4k requests" is a good test case.
### Use `split`
Avoid using regex, `split` is used to extract protocol data. Some performance might be squeezed by avoiding conversion from `SubString` to `String` but it will be observable only for huge payloads.
### Validation
Avoids regex as well if possible.
Name regex: `^[^.*>]+$`
```
julia> function validate_name(name::String)
isempty(name) && error("Name is empty.")
for c in name
if c == '.' || c == '*' || c == '>'
error("Name \"$name\" contains invalid character '$c'.")
end
end
true
end
validate_name (generic function with 1 method)
julia> function validate_name_regex(name::String)
m = match(r"^[^.*>]+$", name)
isnothing(m) && error("Invalid name.")
true
end
validate_name_regex (generic function with 1 method)
julia> using BenchmarkTools
julia> name = "valid_name"
"valid_name"
julia> @btime validate_name(name)
9.593 ns (0 allocations: 0 bytes)
true
julia> @btime validate_name_regex(name)
114.174 ns (3 allocations: 176 bytes)
true
```
### Use strings not raw bytes
Parser is not returning raw bytes but rather `String`. This fast thanks to how `String` constructor works.
```julia-repl
julia> bytes = UInt8['a', 'b', 'c'];
julia> str = String(bytes)
"abc"
julia> bytes
UInt8[]
julia> @doc String
...
When possible, the memory of v will be used without copying when the String object is created.
This is guaranteed to be the case for byte vectors returned by take! on a writable IOBuffer
and by calls to read(io, nb). This allows zero-copy conversion of I/O data to strings. In
other cases, Vector{UInt8} data may be copied, but v is truncated anyway to guarantee
consistent behavior.
...
```
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 1628 | # Quick start
Start nats-server:
```
docker run -p 4222:4222 nats:latest
```
## Check ping - pong working
```@repl
using NATS
nc = NATS.connect()
@time NATS.ping(nc) # First one may be slow due to compilation
@time NATS.ping(nc)
```
## Publish subscribe
```@repl
using NATS
nc = NATS.connect()
sub = subscribe(nc, "test_subject") do msg
@show payload(msg)
end
publish(nc, "test_subject", "Hello.")
sleep(0.2) # Wait for message.
drain(nc, sub)
publish(nc, "test_subject", "Hello.") # Ater drain msg won't be delivared.
```
## Request reply
```bash
> nats reply help.please 'OK, I CAN HELP!!!'
20:35:19 Listening on "help.please" in group "NATS-RPLY-22"
```
```@repl
using NATS
nc = NATS.connect()
rep = @time NATS.request(nc, "help.please");
payload(rep)
```
## Work queues
If `subscription` or `reply` is configured with `queue_group`, messages will be distributed equally between subscriptions with the same group.
```@repl
using NATS
connection = NATS.connect()
sub1 = reply(connection, "some_subject"; queue_group="group1") do
"Reply from worker 1"
end
sub2 = reply(connection, "some_subject"; queue_group="group1") do
"Reply from worker 2"
end
@time request(String, connection, "some_subject")
@time request(String, connection, "some_subject")
@time request(String, connection, "some_subject")
@time request(String, connection, "some_subject")
@time request(String, connection, "some_subject")
@time request(String, connection, "some_subject")
@time request(String, connection, "some_subject")
@time drain(connection, sub1)
@time drain(connection, sub2)
```
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 8285 | # NATS.jl - NATS client for Julia.
NATS.jl allows to connect to [NATS](https://nats.io) cluster from Julia and use
patterns like [publish-subscribe](https://docs.nats.io/nats-concepts/core-nats/pubsub),
[request-reply](https://docs.nats.io/nats-concepts/core-nats/reqreply), and
[queue groups](https://docs.nats.io/nats-concepts/core-nats/queue).
> **Warning**
>
> NATS is not a reliable communication protocol by design. Just like raw TCP connection it provides just at most once message delivery guarantees.
> For reliable communication you need to implement message acknowledgements in client applications or use JetStream protocol build on top of NATS.
## Architecture overview
Each connection creates several asynchronous tasks for monitoring connection state, receiving messages from server, publishing messages to server. Flow is like this:
1. Connect method is called
2. Task for monitoring connection state is created
3. Above task spawns two more tasks for inbound and outbound communication
4. If any of tasks fails monitoring task tries to reconnect by spawning them again
Those tasks should be scheduled on interactive threads to ensure fast responses to server, for instance, in case of [PING](https://jakubwro.github.io/NATS.jl/dev/protocol/#NATS.Ping) message. To not block them tasks handling actual processing of subscription messages are ran in `:default` threadpool. Implication of this to ensure everything works smoothly user should do one of things:
- start `julia` with at least one interactive thread, see `--threads` option
- ensure all handler methods are not CPU intensive if ran with single thread
## Interrupt handling
Graceful handling of interrupt is important in scenario of deployment to `kubernetes` cluster to handle pods auto scaling.
There are several issues with Julia if it comes to handling signals:
1. by default when SIGINT is delivered process is exited immediately, this can be prevented by calling `Base.exit_on_sigint` with `false` parameter.
2. even when this is configured interrupts are delivered to all tasks running on thread 1. Depending on `--threads` configuration this thread might run all tasks (when `--threads 1` which is default) or it can handle tasks scheduled on interactive threadpool (with `--threads M,N` where N is number of interactive threads).
To workaround this behavior all tasks started by `NATS.jl` are started inside `disable_sigint` wrapper, exception to this is special task designated to handling interrupts and scheduled on thread 1 with `sticky` flag set to `true`, what is achieved with `@async` macro.
Limitation to this approach is that tasks started by user of `NATS.jl` or other packages may start tasks that will intercept `InterruptException` may ignore it or introduce unexpected behavior. On user side this might be mitigated by wrapping tasks functions into `disable_sigint`, also entrypoint to application should do this or handle interrupt correctly, for instance by calling `NATS.drain` to close all connections and wait until it is done.
Future improvements in this matter might be introduced by [open PR](https://github.com/JuliaLang/julia/pull/49541)
Current `NATS.jl` approach to handling signals is based on code and discussions from this PR.
## List of all environment variables
| `ENV` variable | Used in | Default if not set | Description
|-----------------------------------------------|--------------|--------------------|-------------
| `NATS_AUTH_TOKEN` | `connect` | `nothing` | Client authorization token
| `NATS_CONNECT_URL` | `connect` | `localhost:4222` | Connection url, multiple urls to the same NATS cluster can be provided, for example `nats:://localhost:4222,tls://localhost:4223`
| `NATS_DRAIN_POLL_INTERVAL_SECONDS` | `connect` | `0.2` | Interval in seconds how often `drain` will check if all buffers are consumed.
| `NATS_DRAIN_TIMEOUT_SECONDS` | `connect` | `5.0` | Maximum time (in seconds) `drain` will block before returning error
| `NATS_ENQUEUE_WHEN_DISCONNECTED` | `connect` | `true` | Allows buffering outgoing messages during disconnection
| `NATS_IGNORE_ADVERTISED_SERVERS` | `connect` | `false` | Ignores other cluster servers returned by server
| `NATS_JWT` | `connect` | `nothing` | The JWT that identifies a user permissions and account
| `NATS_MAX_PINGS_OUT` | `connect` | `3` | How many pings in a row might fail before connection will be restarted
| `NATS_NKEY` | `connect` | `nothing` | The public NKey to authenticate the client
| `NATS_NKEY_SEED` | `connect` | `nothing` | the private NKey to authenticate the client
| `NATS_PASS` | `connect` | `nothing` | Connection password, can be also passed in url `nats://john:passw0rd@localhost:4223` but env variable has higher priority
| `NATS_PEDANTIC` | `connect` | `false` | Turns on additional strict format checking, e.g. for properly formed subjects
| `NATS_PING_INTERVAL` | `connect` | `120.0` | Interval in seconds how often server should be pinged to check connection health
| `NATS_RECONNECT_FACTOR` | `connect` | `5.0` | Exponential reconnect delays configuration
| `NATS_RECONNECT_FIRST_DELAY` | `connect` | `0.1` | Exponential reconnect delays configuration
| `NATS_RECONNECT_JITTER` | `connect` | `0.1` | Exponential reconnect delays configuration
| `NATS_RECONNECT_MAX_DELAY` | `connect` | `5.0` | Exponential reconnect delays configuration
| `NATS_RECONNECT_RETRIES` | `connect` | `220752000000000000` | Exponential reconnect delays configuration
| `NATS_REQUEST_TIMEOUT_SECONDS` | `request` | `5.0` | Time how long `request` will block before returning error
| `NATS_RETAIN_SERVERS_ORDER` | `connect` | `false` | Changes connection url selection policy from random to sequence they were provided.
| `NATS_RETRY_ON_INIT_FAIL` | `connect` | `false` | If set to true `connect` will not throw and error if connection init fails, but will continue retrying in background returning immediately connection in `CONNECTING` state.
| `NATS_SEND_BUFFER_LIMIT_BYTES` | `connect` | `2097152` | Soft limit for buffer of messages pending. If too small operations that send messages to server (e.g. `publish`) may throw an exception
| `NATS_SUBSCRIPTION_CHANNEL_SIZE` | `subscribe` | `524288` | How many messages waiting for processing subscription buffer can hold, if it gets full messages will be dropped.
| `NATS_SUBSCRIPTION_ERROR_THROTTLING_SECONDS` | `subscribe` | `5.0` | How often subscription handler exceptions are reported in logs
| `NATS_TLS_CA_PATH` | `connect` | `nothing` | Path to CA certificate file if TLS is used
| `NATS_TLS_CERT_PATH` | `connect` | `nothing` | Path to client certificate file if TLS is used
| `NATS_TLS_KEY_PATH` | `connect` | `nothing` | Path to client private certificate file if TLS is used
| `NATS_TLS_REQUIRED` | `connect` | `false` | Forces TLS connection. TLS can be also forced by using url with `tls` scheme, example `tls://localhost:4223`
| `NATS_USER` | `connect` | `nothing` | Connection username, can be also passed in url `nats://john:passw0rd@localhost:4223` but env variable has higher priority
| `NATS_VERBOSE` | `connect` | `false` | Turns on protocol acknowledgements
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 1471 | # Handling SIGINT
When SIGINT is delivered, for instance when pressing `CTRL+C` in interactive session or externally by container runtime (for instance Kubernetes pod autoscaller) it is hard to ensure proper action is executed.
Julia tasks might be scheduled on two threadpools, `:interactive` and `:default` and sizes of those threadpools are configured by `--threads` option. First one is intended to run short interactive tasks (like network communication), second one is for more CPU intensive operations that might block a thread for longer time.
When `SIGINT` is delivered it is delivered only to the first thread and which threadpool it handles depends on `--threads` configuration.
For instance:
- `--threads 1` runs 0 `:interactive` threads and 1 `:default` threads.
- `--threads 1,1` runs 1 `:interactive` threads and 1 `:default` threads.
- `--threads 2,3` runs 3 `:interactive` threads and 2 `:default` threads.
To ensure `drain` in `NATS` action is executed on interrupt signal `julia` should be run with exactly one `:interactive` thread. Otherwise some cpu intensive tasks may be scheduled on the first thread, or in case when there are more than one interactive threads, handler might be scheduled on different thread and miss interrupt signal.
To ensure signal is delivered to the tasks that knows how to handle it, all `:interactive` tasks are wrapped into `disable_sigint` method except the one that have proper logic for connection draining.
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 133 |
# Protocol messages
```@docs
NATS.Info
NATS.Connect
NATS.Pub
NATS.Sub
NATS.Unsub
NATS.Msg
NATS.Ping
NATS.Pong
NATS.Err
NATS.Ok
```
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 370 |
# Publish - Subscribe
Functions implementing [NATS Publish-Subscribe](https://docs.nats.io/nats-concepts/core-nats/pubsub) distribution model. For [queue group](https://docs.nats.io/nats-concepts/core-nats/queue) `1:1` instead of default `1:N` fanout configure subscriptions with the same `queue_group` argument.
```@docs
publish
subscribe
next
unsubscribe
drain
```
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 151 |
# Request - Reply
Functions implementing [Request-Reply](https://docs.nats.io/nats-concepts/core-nats/reqreply) pattern.
```@docs
request
reply
```
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 751 | # Scoped connection
This feature allows to use implicit connection in a block of code. It utilizes [ScopedValues](https://github.com/vchuravy/ScopedValues.jl) package.
## Functions
```@docs
with_connection
```
## Examples
```@repl
using NATS
conn1 = NATS.connect()
conn2 = NATS.connect()
with_connection(conn1) do
sub = subscribe("foo") do msg
@show payload(msg)
end
sleep(0.1) # Wait some time to let server process sub.
with_connection(conn2) do
publish("foo", "Some payload")
end
sleep(0.1) # Wait some time to message be delivered.
unsubscribe(sub)
nothing
end
conn1.stats.msgs_received == 1
conn1.stats.msgs_published == 0
conn2.stats.msgs_received == 0
conn2.stats.msgs_published == 1
``` | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 183 | # Consumer
```@docs
ConsumerConfiguration
```
## Management
```@docs
consumer_create
consumer_update
consumer_delete
```
## Subscriptions
```@docs
consumer_next
consumer_ack
```
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 277 | # JetChannel
## Example
```@repl
using NATS
using NATS.JetStream
nc = NATS.connect()
ch = JetChannel{String}(nc, "example_jetstream_channel");
put!(ch, "test");
take!(ch)
t = @async take!(ch)
sleep(1)
istaskdone(t)
put!(ch, "some value");
sleep(0.1)
t.result
destroy!(ch)
``` | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 2127 | # JetDict
## Basic usage
```@repl
using NATS
using NATS.JetStream
nc = NATS.connect()
kv = JetDict{String}(nc, "example_kv")
kv["key1"] = "Value 1"
kv["key2"] = "Value 2"
kv
delete!(kv, "key1")
keyvalue_stream_delete(nc, "example_kv")
```
## Key encoding
Keys of keyvalue stream have limitations. They cannot start and and with '.' and can contain limited set of characters.
Alowed characters:
- letters
- digits
- `'-', '/', '_', '=', '.'`
To allow arbitrary string as a key `:base64url` `encoding` parameter may be specified.
```@repl
using NATS
using NATS.JetStream
nc = NATS.connect()
kv = JetDict{String}(nc, "example_kv_enc", :base64url)
kv["encoded_key1"] = "Value 1"
kv["!@#%^&"] = "Value 2"
kv["!@#%^&"]
keyvalue_stream_delete(nc, "example_kv_enc")
```
## Custom values
```@repl
using NATS
using NATS.JetStream
import Base: show, convert
struct Person
name::String
age::Int64
end
function convert(::Type{Person}, msg::NATS.Msg)
name, age = split(payload(msg), ",")
Person(name, parse(Int64, age))
end
function show(io::IO, ::NATS.MIME_PAYLOAD, person::Person)
print(io, person.name)
print(io, ",")
print(io, person.age)
end
nc = NATS.connect()
kv = JetDict{Person}(nc, "people")
kv["jakub"] = Person("jakub", 22)
kv["martha"] = Person("martha", 22)
kv["martha"]
kv
keyvalue_stream_delete(nc, "people")
```
## Watching changes
```@repl
using NATS
using NATS.JetStream
nc = NATS.connect()
kv = JetDict{String}(nc, "example_kv_watch")
sub = watch(kv) do change
@show change
end
@async begin
kv["a"] = "1"
kv["b"] = "2"
delete!(kv, "a")
kv["b"] = "3"
kv["a"] = "4"
end
sleep(1) # Wait for changes
stream_unsubscribe(nc, sub)
keyvalue_stream_delete(nc, "example_kv_watch")
```
## Optimistic concurrency
```@repl
using NATS
using NATS.JetStream
connection = NATS.connect()
kv = JetStream.JetDict{String}(connection, "test_kv_concurrency")
kv["a"] = "1"
@async (sleep(2); kv["a"] = "2")
with_optimistic_concurrency(kv) do
old = kv["a"]
sleep(3)
kv["a"] = "$(old)_updated"
end
kv["a"]
keyvalue_stream_delete(connection, "test_kv_concurrency")
```
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 352 | # Key Value streams
Low level APIs for manipulating KV buckets. See `JetDict` for interface conforming to `Base.AbstractDict`.
## Management
```@docs
keyvalue_stream_create
keyvalue_stream_purge
keyvalue_stream_delete
```
## Manipulating items
```@docs
keyvalue_get
keyvalue_put
keyvalue_delete
```
## Watching changes
```@docs
keyvalue_watch
``` | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 279 | # Streams
```@docs
StreamConfiguration
```
## Management
```@docs
stream_create
stream_update
stream_purge
stream_delete
```
## Subscriptions
```@docs
stream_publish
stream_subscribe
stream_unsubscribe
```
## Messages
```@docs
stream_message_get
stream_message_delete
```
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 121 |
Extract all ENV variables from sources
```
grep -rni 'get(ENV, "NATS_[^"]*' src/* | sed -E 's/.*(NATS_[^"]*).*/\1/'
```
| NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.1.0 | d9d9a189fb9155a460e6b5e8966bf6a66737abf8 | docs | 837 | ```
openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out nats.crt -keyout nats.key -addext "subjectAltName = DNS:localhost, DNS:nats"
```
```
openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -CA nats.crt -CAkey nats.key -nodes -out client.crt -keyout client.key -addext "subjectAltName = DNS:localhost, email:jakub@localhost"
```
```
docker create -v $(pwd)/test/certs:/certs -v $(pwd)/test/configs/nats-server-tls-auth.conf:/nats-server.conf -p 4225:4222 nats
```
```
docker create -p 4223:4222 -v $(pwd)/test/certs:/certs -it nats --tls --tlscert /certs/nats.crt --tlskey /certs/nats.key
```
```
nats reply help.please 'OK, I CAN HELP!!!' --server localhost:4223 --tlsca test/certs/nats.crt
```
```
docker create -v $(pwd)/test/configs/nats-server-nkey-auth.conf:/nats-server.conf -p 4224:4222 nats
``` | NATS | https://github.com/jakubwro/NATS.jl.git |
|
[
"MIT"
] | 0.2.0 | be4399b63af93efd1969fa96a77bbd602056916c | code | 526 | using Documenter
using GoogleDrive
makedocs(
modules = [GoogleDrive],
sitename = "GoogleDrive.jl",
pages = [
"Home" => "index.md",
"Features" => "features.md",
"Methods" => "methods.md",
],
)
deploydocs(
repo = "github.com/JuliaIO/GoogleDrive.jl.git",
devbranch = "master",
target = "build",
branch = "gh-pages",
# latest = "master",
# osname = "linux"
devurl = "dev",
versions = ["stable" => "v^", "dev" => "dev"],
forcepush = true,
push_preview = true,
)
| GoogleDrive | https://github.com/JuliaIO/GoogleDrive.jl.git |
|
[
"MIT"
] | 0.2.0 | be4399b63af93efd1969fa96a77bbd602056916c | code | 2163 | module GoogleDrive
using Base: AbstractCmd
using Downloads: download
export google_download, google_download_url
"""
google_download(url::AbstractString, location::Union{AbstractString,AbstractCmd,IO})
Download data from Google URL `url` into `location`, returning `location`.
`location` can be of any type that `Downloads.download` accepts - so a file
path, a command, or an IO buffer.
"""
function google_download(url::AbstractString, location::Union{AbstractString,AbstractCmd,IO})
url = google_download_url(url)
return download(url, location)
end
"""
google_download_url(url::AbstractString)
Convert a direct Google Drive/Sheets URL to a direct download
URL. The resulting URL can be used with `Downloads`, `DataDeps`
or any other data fetching package.
"""
function google_download_url(url::AbstractString)
if is_drive_url(url)
url = drive_download_url(url)
elseif is_sheet_url(url)
url = sheet_download_url(url)
else
throw(ArgumentError("Unknown URL form $url"))
end
end
is_sheet_url(url) = occursin("docs.google.com/spreadsheets", url)
const _drive_pattern = r"^https?:\/\/drive\.google\.com\/file\/d\/([^\/]*).*"
is_drive_url(url) = occursin(_drive_pattern, url) || occursin("docs.google.com/uc", url)
"""
drive_download_url(url::AbstractString)::String
Convert a GoogleDrive URL of the form
`https://drive.google.com/file/d/XYZ`
to the form needed for raw data download:
`https://docs.google.com/uc?export=download&id=XYZ`
"""
function drive_download_url(url::AbstractString)
full_url = s"https://docs.google.com/uc?export=download&id=\1"
return replace(url, _drive_pattern => full_url)
end
"""
sheet_download_url(url::AbstractString, format)::String
Convert a Google Sheets URL of the form
`https://docs.google.com/spreadsheets/d/XYZ/edit`
to the form needed for raw data download:
`https://docs.google.com/spreadsheets/d/XYZ/export?format=FORMAT`
"""
function sheet_download_url(url::AbstractString, format="csv")
link, action = splitdir(url)
if !startswith(action, "export")
url = link * "/export?format=$format"
end
return url
end
end # Module
| GoogleDrive | https://github.com/JuliaIO/GoogleDrive.jl.git |
|
[
"MIT"
] | 0.2.0 | be4399b63af93efd1969fa96a77bbd602056916c | code | 974 | using GoogleDrive
using Test
@testset "GoogleDrive.jl" begin
dst = "https://docs.google.com/uc?export=download&id=XYZ"
@test google_download_url("https://drive.google.com/file/d/XYZ") == dst
@test google_download_url("https://drive.google.com/file/d/XYZ/view") == dst
@test google_download_url(dst) == dst
src = "https://docs.google.com/spreadsheets/d/XYZ/edit"
dst = "https://docs.google.com/spreadsheets/d/XYZ/export?format="
@test google_download_url(src) == dst * "csv"
@test GoogleDrive.sheet_download_url(src, "xlsx") == dst * "xlsx"
@test_throws ArgumentError google_download_url("foo")
#=
The following test reads a small Julia file from GoogleDrive.
The test will fail if that Julia file ever disappears.
=#
url = "https://drive.google.com/file/d/1GqmszfSB_LHGQEQpSjoiPyDROZ5a8Ls4"
io = IOBuffer()
google_download(url, io) # mutates io
str = String(take!(io))
@test str[1:2] == "#="
end
| GoogleDrive | https://github.com/JuliaIO/GoogleDrive.jl.git |
|
[
"MIT"
] | 0.2.0 | be4399b63af93efd1969fa96a77bbd602056916c | docs | 2774 | # GoogleDrive
Download files from Google Drive.
https://github.com/JuliaIO/GoogleDrive.jl
[![action status][action-img]][action-url]
[![pkgeval status][pkgeval-img]][pkgeval-url]
[![codecov][codecov-img]][codecov-url]
[![license][license-img]][license-url]
[![docs-stable][docs-stable-img]][docs-stable-url]
[![docs-dev][docs-dev-img]][docs-dev-url]
## Introduction
GoogleDrive.jl provides support for downloading files from Google Drive and Google Sheets.
### Installation
Install the package using the
[julia package manager](https://julialang.github.io/Pkg.jl/v1/managing-packages/#Adding-packages-1):
Open the REPL, press <kbd>]</kbd> to enter package mode, and then:
```julia
pkg> add GoogleDrive
```
## Details
To download data into an IO stream from a special URL of the form
`url = "https://docs.google.com/uc?export=download&id=1GqmszfSB_LHGQEQpSjoiPyDROZ5a8Ls4"`,
use the following code:
```julia
using Downloads: download
io = IOBuffer()
download(url, io)
str = String(take!(io)) # (this line for text data only)
```
To download data from a typical Google Drive URL of the form
`url = "https://drive.google.com/file/d/1GqmszfSB_LHGQEQpSjoiPyDROZ5a8Ls4"`,
use the following code
that converts the URL internally for convenience:
```julia
using GoogleDrive: google_download
io = IOBuffer()
google_download(url, io)
str = String(take!(io)) # (this line for text data only)
```
## Contributing and Reporting Bugs
Contributions, in the form of bug-reports, pull requests, additional documentation are encouraged. They can be made to the Github repository.
**All contributions and communications should abide by the
[Julia Community Standards](https://julialang.org/community/standards/).**
<!-- URLs -->
[action-img]: https://github.com/JuliaIO/GoogleDrive.jl/workflows/CI/badge.svg
[action-url]: https://github.com/JuliaIO/GoogleDrive.jl/actions
[build-img]: https://github.com/JuliaIO/GoogleDrive.jl/workflows/CI/badge.svg?branch=master
[build-url]: https://github.com/JuliaIO/GoogleDrive.jl/actions?query=workflow%3ACI+branch%3Amaster
[pkgeval-img]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/G/GoogleDrive.svg
[pkgeval-url]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/G/GoogleDrive.html
[codecov-img]: https://codecov.io/github/JuliaIO/GoogleDrive.jl/coverage.svg?branch=master
[codecov-url]: https://codecov.io/github/JuliaIO/GoogleDrive.jl?branch=master
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://JuliaIO.github.io/GoogleDrive.jl/stable
[docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg
[docs-dev-url]: https://JuliaIO.github.io/GoogleDrive.jl/dev
[license-img]: https://img.shields.io/badge/license-MIT-brightgreen.svg
[license-url]: LICENSE
| GoogleDrive | https://github.com/JuliaIO/GoogleDrive.jl.git |
|
[
"MIT"
] | 0.2.0 | be4399b63af93efd1969fa96a77bbd602056916c | docs | 650 | ## functions
### google_download
`google_download(URL, IO)`
Download a file from Google Drive or Google Sheets.
#### Example
Downloading a ZIP file from Drive using the `google_download` function
```
julia> google_download("https://drive.google.com/file/d/0B9w48e1rj-MOLVdZRzFfTlNsem8/view", "file.zip")
"/home/iamtejas/Downloads/file.zip"
```
### google_download_url
Convert a direct Google Drive / Google Sheets URL to the direct download form.
#### Example
```
julia> google_download_url("https://drive.google.com/file/d/0B9w48e1rj-MOLVdZRzFfTlNsem8/view")
"https://docs.google.com/uc?export=download&id=0B9w48e1rj-MOLVdZRzFfTlNsem8"
```
| GoogleDrive | https://github.com/JuliaIO/GoogleDrive.jl.git |
|
[
"MIT"
] | 0.2.0 | be4399b63af93efd1969fa96a77bbd602056916c | docs | 573 | # GoogleDrive.jl Documentation
```@contents
Pages = ["features.md"]
Depth=4
```
## Preface
This manual is designed to get you started using GoogleDrive.jl Package in Julia.
## Installation
The package can be installed by cloning git repo in .julia/dev/
```julia
~/.julia/dev> git clone <fork_repo_URL>
```
## Getting Started
In all of the examples that follow, we'll assume that you have the
TextAnalysis package fully loaded. This means that we think you've
implicitly typed
```julia
julia> using GoogleDrive
```
before every snippet of code.
```@index
```
| GoogleDrive | https://github.com/JuliaIO/GoogleDrive.jl.git |
|
[
"MIT"
] | 0.2.0 | be4399b63af93efd1969fa96a77bbd602056916c | docs | 91 | ## Methods list
```@index
```
## Methods usage
```@autodocs
Modules = [GoogleDrive]
```
| GoogleDrive | https://github.com/JuliaIO/GoogleDrive.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 787 | using Documenter #, DocumenterLaTeX
using FiniteStateTransducers
makedocs(
sitename = "FiniteStateTransducers",
format = [Documenter.HTML()],#, DocumenterLaTeX.LaTeX()],
authors = "Niccolò Antonello",
modules = [FiniteStateTransducers],
pages = [
"Home" => "index.md",
"Introduction" => "1_intro.md",
"Weights" => "2_semirings.md",
"Contructing WFSTs" => "3_wfsts.md",
"Algorithms" => "4_algorithms.md",
"I/O" => "5_io.md",
],
doctest=false,
)
# Documenter can also automatically deploy documentation to gh-pages.
# See "Hosting Documentation" and deploydocs() in the Documenter manual
# for more information.
deploydocs(
repo = "github.com/idiap/FiniteStateTransducers.jl.git",
devbranch = "main",
)
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1456 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
module FiniteStateTransducers
using DataStructures
# semirings
include("semirings/semirings.jl")
include("semirings/probability.jl")
include("semirings/log.jl")
include("semirings/nlog.jl")
include("semirings/tropical.jl")
include("semirings/boolean.jl")
include("semirings/leftstring.jl")
include("semirings/rightstring.jl")
include("semirings/product.jl")
include("semirings/convert.jl")
include("epsilon.jl")
include("arc.jl")
include("wfst.jl")
include("path.jl")
include("sym.jl")
include("show.jl")
include("properties.jl")
include("other_constr.jl")
include("io_wfst.jl")
include("iterators/dfs.jl")
include("iterators/bfs.jl")
include("iterators/composeiterator.jl")
include("algorithms/allpaths.jl")
include("algorithms/rm_state.jl")
include("algorithms/is_visited.jl")
include("algorithms/get_scc.jl")
include("algorithms/connect.jl")
include("algorithms/shortest_distance.jl")
include("algorithms/permute_states.jl")
include("algorithms/topsort.jl")
include("algorithms/rm_eps.jl")
include("algorithms/determinize.jl")
include("algorithms/arcmap.jl")
include("algorithms/inv.jl")
include("algorithms/proj.jl")
include("algorithms/reverse.jl")
include("algorithms/closure.jl")
include("algorithms/compositionfilters.jl")
include("algorithms/compose.jl")
include("algorithms/cat.jl")
include("algorithms/wfst2tr.jl")
end # module
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 2280 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export Arc, get_ilabel, get_olabel, get_weight, get_nextstate
"""
`Arc(ilab::Int,olab::Int,w::W,n::Int)`
Constructs an arc with input label `ilab`, output label `olab`, weight 'weight' and nextstate `n`.
`ilab` and `olab` must be integers consistent with a input/output symbol table of the WFST at use.
Mainly used for internals see [`add_arc!`](@ref) for a simpler way of adding arcs to a WFST.
"""
struct Arc{W,D}
ilabel::D # input label
olabel::D # output label
weight::W # weight
nextstate::D # destination id
end
import Base: ==
function ==(a::Arc,b::Arc; check_weight=true)
i = (a.ilabel == b.ilabel)
o = (a.olabel == b.olabel)
d = (a.nextstate == b.nextstate)
if check_weight
w = (a.weight == b.weight)
return i && o && d && w
else
return i && o && d
end
end
function Base.show(io::IO, A::Arc, isym::Dict, osym::Dict)
ilabel = idx2string(A.ilabel,isym)
olabel = idx2string(A.olabel,osym)
print(io, "$(ilabel):$(olabel)/$(A.weight) → ($(A.nextstate))")
end
function Base.show(io::IO, A::Arc)
print(io, "$(A.ilabel):$(A.olabel)/$(A.weight) → ($(A.nextstate))")
end
function idx2string(label,sym)
if iseps(label)
return "ϵ"
else
return "$(sym[label])"
end
end
"""
`get_ilabel(A::Arc)`
Returns the input label index of the arc `A`.
"""
get_ilabel(A::Arc) = A.ilabel
"""
`get_olabel(A::Arc)`
Returns the input label index of the arc `A`.
"""
get_olabel(A::Arc) = A.olabel
"""
`get_weight(A::Arc)`
Returns the weight the arc `A`.
"""
get_weight(A::Arc) = A.weight
"""
`get_nextstate(A::Arc)`
Returns the state that the arc `A` is pointing to.
"""
get_nextstate(A::Arc) = A.nextstate
change_next(a::Arc{W,D}, nextstate::D) where {W,D} = Arc{W,D}(get_ilabel(a),
get_olabel(a),
get_weight(a),
nextstate)
Base.inv(a::Arc) = Arc(get_olabel(a),get_ilabel(a),get_weight(a),get_nextstate(a))
proj(a::Arc, get_iolabel::Function) = Arc(get_iolabel(a),get_iolabel(a),get_weight(a),get_nextstate(a))
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 799 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export iseps
"""
`iseps(x)`
Checks if `x` is the epsilon label. Defined only for `String` and `Int`, where `<eps>` and `0` are the epsilon symbols. Extend this method if you want to create WFST with a user defined type.
"""
iseps(x::T) where {T<:Integer} = x == zero(T)
iseps(x::String) = x == "<eps>"
iseps(x::Char) = x == 'ϵ'
export get_eps
"""
`get_eps(x::Type)`
Returns the epsilon label for a given `Type`. Defined only for `String` and `Int`, where `<eps>` and `0` are the epsilon symbols. Extend this method if you want to create WFST with a user defined type.
"""
get_eps(x::Type{T}) where {T<:Integer} = T(0)
get_eps(x::Type{String}) = "<eps>"
get_eps(x::Type{Char}) = 'ϵ'
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 3531 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export txt2fst
"""
`txt2fst(path,isym[,osym];W=TropicalWeight{Float32})`
Loads a WFST from a text file using [OpenFST format](http://openfst.org/twiki/bin/view/FST/FstQuickTour).
`isym` and `osym` can be either dictionaries or paths to the input/output symbol list.
"""
function txt2fst(path::AbstractString,
isym::AbstractDict,
osym::AbstractDict;W=TropicalWeight{Float32})
fst = WFST(isym,osym; W=W)
fst_txt = read(path, String)
for x in split(fst_txt,"\n"; keepempty=false)
arc = split(x)
s = parse(Int,arc[1])+1
if length(arc) <= 2 # final node with no weight
N =s-length(fst)
if N > 0
add_states!(fst,N)
end
w = length(arc) == 2 ? parse(W,arc[2]) : one(W)
final!(fst,s,w)
elseif length(arc) >= 4
n = parse(Int,arc[2])+1
i = typeof(arc[3]) <: AbstractString ? String(arc[3]) : parse(I,arc[3])
o = typeof(arc[4]) <: AbstractString ? String(arc[4]) : parse(O,arc[4])
w = length(arc) == 5 ? parse(W,arc[5]) : one(W)
add_arc!(fst,s,n,i,o,w.x)
end
end
initial!(fst,1)
return fst
end
txt2fst(path::AbstractString,isym::AbstractDict; kwargs...) =
txt2fst(path,isym,isym; kwargs...)
txt2fst(path::AbstractString,path_sym::AbstractString; kwargs...) =
txt2fst(path,txt2sym(path_sym); kwargs...)
txt2fst(path::AbstractString,path_isym::AbstractString,path_osym::AbstractString; kwargs...) =
txt2fst(path,txt2sym(path_isym),txt2sym(path_osym); kwargs...)
export txt2sym
"""
`txt2sym(path)`
Loads a symbol list from a text file into a `Dict` using [OpenFST convention](http://openfst.org/twiki/bin/view/FST/FstQuickTour).
"""
function txt2sym(path)
sym_txt = read(path,String)
sym = Dict{String,Int}()
for x in split(sym_txt,"\n"; keepempty=false)
z = strip.(split(x))
if length(z) > 2
throw(ErrorException("Invalid symbol table `$x` in `$path`"))
end
if z[1] != "<eps>"
sym[String(z[1])] = parse(Int,z[2])
end
end
return sym
end
export fst2dot
"""
`fst2dot(fst)`
Converts the `fst` to a string in the [dot format](https://graphviz.org/doc/info/lang.html).
Useful to visualise large FSTs using Graphviz.
"""
function fst2dot(fst::WFST)
x = "digraph FST {\nrankdir=LR;\nbgcolor=\"transparent\"\n;\ncenter=1;\n"
int2isym = get_iisym(fst)
int2osym = get_iosym(fst)
for (i,s) in enumerate(fst)
if isfinal(fst,i)
w = get_final_weight(fst,i)
x *= "$i [label = \"$(i)/$(w)\", shape = circle, style = bold, fontsize = 14]\n"
elseif isinitial(fst,i)
w = get_initial_weight(fst,i)
x *= "$i [label = \"$(i)/$(w)\", shape = doublecircle, style = solid, fontsize = 14]\n"
else
x *= "$i [label = \"$(i)\", shape = circle, style = solid, fontsize = 14]\n"
end
for arc in s
ilabel = idx2string(get_ilabel(arc),int2isym)
olabel = idx2string(get_olabel(arc),int2osym)
n = get_nextstate(arc)
w = get_weight(arc)
x*="\t$(i) -> $(n) [label = \"$(ilabel):$(olabel)/$(w)\", fontsize = 14];\n"
end
end
x *="}"
return x
end
export fst2pdf
"""
`fst2pdf(fst,pdffile)`
Prints the `fst` to a pdf file using [Graphviz](https://graphviz.org/).
Requires Graphviz to be intalled.
"""
function fst2pdf(fst,file)
tmp = mktempdir()
dot = fst2dot(fst)
dotfile = joinpath(tmp,"fst.dot")
write(dotfile,dot)
write(file, read(`dot -Tpdf $dotfile`))
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 2003 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export linearfst
"""
`linearfst(ilabels,olabels,w,isym,[osym])`
Creates a linear WFST. `ilabels`, `olabels` and `w` are the input labels, output labels and weights respectively which must be vectors of the same size.
Keyword arguments are the same of `WFST` constructor.
"""
function linearfst(ilabels::AbstractVector,
olabels::AbstractVector,
w::AbstractVector{W},
isym::AbstractDict,
osym::AbstractDict) where {W}
N = length(w)
if !(length(ilabels) == length(olabels) == N)
throw(ErrorException("`ilabels`, `olabels`, and `w` must have all the same lengths"))
end
fst = WFST(isym,osym; W = W)
for i = 1:N
add_arc!(fst, i, i+1, ilabels[i], olabels[i], w[i])
end
initial!(fst,1)
final!(fst,length(w)+1)
return fst
end
linearfst(ilabels,olabels,w,isym) =
linearfst(ilabels,olabels,w,isym,isym)
export matrix2wfst
"""
`matrix2wfst(isym,[osym,] X; W = TropicalWeight{Float32})`
Creates a WFST with weight type `W` and input output tables `isym` and `osym` using the matrix `X`.
If `X` is a matrix of dimensions `Ns`x`Nt`, the resulting fst will have `Nt+1` states.
Arcs form the `t`-th state of `fst` will go only to the `t+1`-th state and will correspond to the non-zero element of the `t`-th column of `X`.
State `1` and `Nt+1` are initial and final state, respectively.
"""
function matrix2wfst(isym::AbstractDict{I,D},
osym::AbstractDict{O,D},
X::AbstractMatrix; W = TropicalWeight{Float32}) where {D,I,O}
fst = WFST(isym, osym; W = W)
Ns, Nt = size(X)
add_states!(fst,Nt+1)
for t = 1:Nt, j = 1:Ns
if W(X[j,t]) != zero(W)
arc = Arc{W,D}(j,j,W(X[j,t]),t+1)
push_arc!(fst,t,arc)
end
end
initial!(fst,1)
final!(fst,Nt+1)
return fst
end
matrix2wfst(isym,X;kwargs...) = matrix2wfst(isym,isym,X;kwargs...)
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 3157 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export Path
mutable struct Path{W,D <: Integer,I,O,
IS <: AbstractDict{I,D}, OS <: AbstractDict{O,D}}
ilabels::Vector{D} # here we only use Int
olabels::Vector{D}
weight::W
isym::IS # input symbol table idx::Int => sym::I
osym::OS # output symbol table idx::Int => sym::O
end
"""
`Path(isym[,osym], iolabel::Pair, w=one(TropicalWeight{Float32}))`
Construct a path with input and output symbol table `isym` and (optional) `osym` (see [`WFST`](@ref)).
`iolabel` is a `Pair` of vectors.
```julia
julia> isym = ["a","b","c","d"];
julia> osym = ["α","β","γ","δ"];
julia> W = ProbabilityWeight{Float32};
julia> p = Path(isym,osym,["a","b","c"] => ["α","β","γ"], one(W))
["a", "b", "c"] → ["α", "β", "γ"], w:1.0f0
```
The weight of a path of a WFST results from the multiplication (``\\otimes``) of the weights of the different arcs that are transversed. See e.g. [`get_paths`](@ref) to extract paths from a WFST.
```julia
julia> p * Path(isym,osym,["d"] => ["δ"], W(0.5))
["a", "b", "c", "d"] → ["α", "β", "γ", "δ"], w:0.5f0
```
"""
function Path(isym::Dict, osym::Dict, iolabels::Pair, w = one(TropicalWeight{Float32}))
Path([isym[s] for s in iolabels.first],
[osym[s] for s in iolabels.second], w, isym, osym)
end
Path(isym, iolabels::Pair, w = one(TropicalWeight{Float32})) =
Path(isym, isym, iolabels, w)
Path(isym::AbstractVector, osym::AbstractVector, iolabels::Pair, w) =
Path(
Dict( s => i for (i,s) in enumerate(isym)),
Dict( s => i for (i,s) in enumerate(osym)),
iolabels,w)
get_weight(p::Path) = p.weight
get_ilabel(p::Path) = p.ilabels
get_olabel(p::Path) = p.olabels
export get_isequence
"""
`get_isequence(p::Path)`
Returns the input sequence of the path `p`.
"""
function get_isequence(p::Path)
idx2sym = get_iisym(p)
return [idx2sym[idx] for idx in get_ilabel(p)]
end
export get_osequence
"""
`get_osequence(p::Path)`
Returns the output sequence of the path `p`.
"""
function get_osequence(p::Path)
idx2sym = get_iosym(p)
return [idx2sym[idx] for idx in get_olabel(p)]
end
function update_path!(path::Path{W,D}, ilabel::D, olabel::D, w) where {W,D}
if !iseps(ilabel)
push!(path.ilabels, ilabel)
end
if !iseps(olabel)
push!(path.olabels, olabel)
end
update_weight!(path, W(w))
return path
end
function update_path(path,ilabel,olabel,w)
p = deepcopy(path)
update_path!(p,ilabel,olabel,w)
return p
end
update_weight!(path::Path{W}, w::W) where {W} = path.weight *= w
update_weight(path::Path{W}, w::W) where {W} =
Path(path.ilabels,path.olabels,w*path.weight,path.isym,path.osym)
import Base: *
function *(p1::Path, p2::Path)
Path([p1.ilabels; p2.ilabels], [p1.olabels;p2.olabels], p1.weight*p2.weight, p1.isym, p1.osym)
end
import Base: ==
function ==(p1::Path,p2::Path)
if (length(p1.ilabels) == length(p2.ilabels)) &&
(length(p1.olabels) == length(p2.olabels))
return all(p1.ilabels .== p2.ilabels) && all(p1.olabels .== p2.olabels) && (p1.weight == p2.weight)
else
return false
end
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 3783 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export typeofweight
"""
`typeofweight(fst_or_path)`
Returns the weight type of a WFST or a path.
"""
typeofweight(fst::Union{WFST{W},Path{W}}) where {W} = W
export get_ialphabet
"""
`get_ialphabet(label::fst)`
Returns the alphabet of the input labels of `fst`.
The alphabet is defined as the set of symbols composing the input or output labels.
"""
get_ialphabet(fst::WFST) = Set(keys(get_isym(fst)))
export get_oalphabet
"""
`get_oalphabet(label::fst)`
Returns the alphabet of the output labels of `fst`.
The alphabet is defined as the set of symbols composing the input or output labels.
"""
get_oalphabet(fst::WFST) = Set(keys(get_osym(fst)))
export count_eps
"""
`count_eps(label::Function, fst::FST)`
Returns number of epsilon transition of either input or output labels.
To specify input or output plug in `ilabel` and `olabel` respectively in `label`.
"""
function count_eps(label::Function, fst::WFST)
cnt = 0
for state in fst
for arc in state
if iseps(label(arc))
cnt += 1
end
end
end
return cnt
end
export has_eps
"""
`has_eps([label::Function,] fst::FST)`
Check if `fst` has epsilon transition in either input or output labels.
To specify input or output plug in either `get_ilabel` or `get_olabel` respectively in `label`.
"""
function has_eps(label::Function, fst::WFST)
for state in fst
for arc in state
if iseps(label(arc))
return true
end
end
end
return false
end
function has_eps(fst::WFST)
for state in fst
for arc in state
if iseps(get_ilabel(arc))
return true
end
if iseps(get_olabel(arc))
return true
end
end
end
return false
end
export is_acceptor
"""
`is_acceptor(fst::WFST)`
Returns `true` if `fst` is an acceptor, i.e. if all arcs have equal input and output labels.
"""
function is_acceptor(fst::WFST)
acceptor = true
for s in fst
for a in s
acceptor = acceptor && (get_ilabel(a) == get_olabel(a))
if acceptor == false
break
end
end
end
return acceptor
end
export is_deterministic
"""
`is_deterministic(fst::WFST; get_label=get_ilabel)`
Returns `true` if `fst` is deterministic in the input labels.
A input label deterministic WFST must have a single initial state and arcs leaving any state do not share the same input label.
Change the keyword `get_label` to `get_olabel` in order to check determinism in the output labels.
"""
function is_deterministic(fst::WFST; get_label=get_ilabel)
if length(get_initial(fst; single=false)) > 1
return false
end
for s in fst
for i in 1:length(s)
for ii in i+1:length(s)
if get_label(s[i]) == get_label(s[ii])
return false
end
end
end
end
return true
end
export is_acyclic
"""
`is_acyclic(fst::WFST[,i = get_initial(fst;single=true)]; kwargs...)`
Returns the number of states of the fst. For `kwargs` see [`DFS`](@ref).
"""
function is_acyclic(fst::WFST, i = get_initial(fst;single=true); kwargs...)
if isempty(fst)
return true
else
dfs = DFS(fst,i; kwargs...)
for (p,s,n,d,e,a) in dfs
if !d # already discovered states
if !e && !dfs.is_completed[n]
return false
end
end
end
return true
end
end
"""
`length(fst::WFST)`
Returns the number of states of the fst.
"""
Base.length(fst::WFST) = length(get_states(fst))
"""
`size(fst::WFST,[i])`
Returns number of states and total number of arcs in a tuple.
If 'i=1' returns the number of states and if `i=2` the number of arcs.
"""
Base.size(fst::WFST) = (length(get_states(fst)), count_arcs(fst))
Base.size(fst::WFST,i::Int) = size(fst)[i]
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1326 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
function Base.show(io::IO, fst::WFST)
sz = size(fst)
println("WFST #states: $(sz[1]), #arcs: $(sz[2]), #isym: $(length(fst.isym)), #osym: $(length(fst.osym))")
if sz[2] < 100 && !isempty(fst)
int2isym = get_iisym(fst)
int2osym = get_iosym(fst)
for (i,s) in enumerate(fst)
if isinitial(fst,i) && isfinal(fst,i)
wi = get_initial_weight(fst,i)
wf = get_final_weight(fst,i)
println("|(($(i)/$(wi*wf)))|")
elseif isfinal(fst,i)
w = get_final_weight(fst,i)
println("(($(i)/$(w)))")
elseif isinitial(fst,i)
w = get_initial_weight(fst,i)
println("|$(i)/$(w)|")
else
println("($(i))")
end
show_state(io, s, int2isym, int2osym)
end
end
end
function show_state(io::IO, s, int2isym, int2osym)
for arc in s
show(io, arc, int2isym, int2osym)
println()
end
end
function Base.show(io::IO, p::Path)
if length(p.ilabels) + length(p.olabels) < 50
isym = get_iisym(p)
osym = get_iosym(p)
print(io, "$([isym[i] for i in p.ilabels]) → $([osym[i] for i in p.olabels]), w:$(p.weight)" )
else
print(io, " #$(length(p.ilabels)) → #$(length(p.olabels)), w:$(p.weight)" )
end
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 928 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export get_isym
"""
`get_isym(fst::WFST)`
Returns the input symbol table of `fst`. The table consists of a dictionary where each element goes from the symbol to the corresponding index.
"""
get_isym(fst::Union{WFST,Path}) = fst.isym
export get_iisym
"""
`get_iisym(fst::WFST)`
Returns the inverted input symbol table.
"""
get_iisym(fst::Union{WFST,Path}) = Dict(fst.isym[k] => k for k in keys(fst.isym))
export get_osym
"""
`get_osym(fst::WFST)`
Returns the output symbol table of `fst`. The table consists of a dictionary where each element goes from the symbol to the corresponding index.
"""
get_osym(fst::Union{WFST,Path}) = fst.osym
export get_iosym
"""
`get_iosym(fst::WFST)`
Returns the inverted output symbol table.
"""
get_iosym(fst::Union{WFST,Path}) = Dict(fst.osym[k] => k for k in keys(fst.osym))
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 8466 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export WFST
struct WFST{W, A<:Arc{W}, D, I, O,
IS <: AbstractDict{I,D}, OS <: AbstractDict{O,D},
IF <: AbstractDict{D,W},
S <: AbstractVector{<:AbstractVector{A}}
}
states::S
initials::IF # index of initial state and corresponding weights
finals::IF # index of final state and corresponding weights
isym::IS # input symbol table idx::Int => sym::I
osym::OS # output symbol table idx::Int => sym::O
end
"""
`WFST(isym, [osym]; W = TropicalWeight{Float32})`
Construct an empty Weighted Finite State Transducer (WFST)
* `isym` input symbol table (can be a dictionary or a vector)
* `osym` output symbol dictionary (optional)
* `W` weight type
If the symbol table are `AbstractDict{I,D}`, `D` must be an integer and `I` the type of the symbol.
"""
function WFST(isym::Dict{I,D}, osym::Dict{O,D}; W=TropicalWeight{Float32}) where {D<:Integer, I, O}
A = Arc{W,D}
states=Vector{Vector{A}}()
initials=Dict{D,W}()
finals=Dict{D,W}()
WFST(states,initials,finals,isym,osym)
end
parse_sym(sym::AbstractArray) = Dict(s => i for (i,s) in enumerate(sym))
parse_sym(sym::AbstractDict) = sym
parse_sym(sym) = throw(ErrorException("Symbol table must be either a Vector or a Dict"))
WFST(isym;kwargs...) = WFST(isym,isym; kwargs...)
WFST(isym,osym;kwargs...) = WFST(parse_sym(isym),parse_sym(osym);kwargs...)
# methods
export add_states!
"""
`add_states!(fst,N)`
Add `N` empty states to the FST.
"""
function add_states!(fst::WFST{W,A}, N::Int) where {W,A}
s = get_states(fst)
for i = 1:N
push!(s, Vector{A}() )
end
return fst
end
export get_initial
"""
`get_initial(fst::WFST, [single=false])`
Returns the initial state id of the `fst`. If `single` is `true` the first initial state is returned.
"""
function get_initial(fst::WFST; single=true)
if isempty(fst.initials)
throw(ErrorException("No initial state is present"))
end
if single
return first(keys(fst.initials))
else
return fst.initials
end
end
export get_initial_weight
"""
`get_initial_weight(fst::WFST,i)`
Returns the weight of initial `i`-th state of `fst`.
"""
get_initial_weight(fst::WFST,i) = get_initial(fst;single=false)[i]
export isinitial
"""
`isinitial(fst::WFST, i)`
Check if the `i`-th state is an initial state.
"""
isinitial(fst::WFST,i) = i in keys(fst.initials)
export initial!
"""
`initial!(fst::WFST{W},i, [w=one(W)])`
Set the `i`-th state as a initial state. A weight `w` can also be provided.
"""
function initial!(fst::WFST{W}, i, w=one(W)) where {W}
fst.initials[i] = W(w)
return fst
end
export rm_initial!
"""
`rm_initial!(fst,i)`
Remove initial state labeling of the state `i`.
"""
rm_initial!(fst,i) = delete!(fst.initials,i)
export get_final
"""
`get_final(fst::WFST, [single=false])`
Returns the final state id of the `fst`. If `single` is `true` the first final state is returned.
"""
function get_final(fst::WFST; single=false)
if isempty(fst.finals)
throw(ErrorException("No final state is present"))
end
if single
return first(keys(fst.finals))
else
return fst.finals
end
end
export get_final_weight
"""
`get_final_weight(fst::WFST,i)`
Returns the weight of `i`-th final state of `fst`.
"""
get_final_weight(fst::WFST,i) = get_final(fst;single=false)[i]
export isfinal
"""
`isfinal(fst::WFST, i)`
Check if the `i`-th state is an final state.
"""
isfinal(fst::WFST,i) = i in keys(fst.finals)
export final!
"""
`final!(fst::WFST{W},i, [w=one(W)])`
Set the `i`-th state as a final state. A weight `w` can also be provided.
"""
function final!(fst::WFST{W}, i, w) where {W}
fst.finals[i] = W(w)
return fst
end
final!(fst::WFST{W},i) where {W} = final!(fst,i,one(W))
export rm_final!
"""
`rm_final!(fst,i)`
Remove final state labeling of the `i`-th state.
"""
rm_final!(fst::WFST,i) = delete!(fst.finals,i)
export get_states
"""
`get_states(fst::WFST)`
Returns the states the `fst`.
"""
get_states(fst::WFST) = fst.states
export add_arc!
"""
`add_arc!(fst, src, dest, ilabel, olabel[, w=one(W)])`
`add_arc!(fst, srcdest::Pair, ilabelolabel::Pair[, w=one(W)])`
Adds an arc from state `src` to state `dest` with input label `ilabel`, output label `olabel` and weight `w`.
Alternative notation utilizes `Pair`s.
If `w` is not provided this defaults to `one(W)` where `W` is the weight type of `fst`.
"""
function add_arc!(fst::WFST{W},
srcdest::Pair,
iolabel::Pair,
w=one(W)) where {W}
src, dest = srcdest.first, srcdest.second
ilabel, olabel = iolabel.first, iolabel.second
add_arc!(fst,src,dest,ilabel,olabel,w)
end
function parse_label(label,sym)
if label in keys(sym)
idx = sym[label]
elseif iseps(label)
idx = 0
else
throw(ErrorException("Symbol $label not found in symbol table $sym"))
end
return idx
end
function add_arc!(fst::WFST{W,A},
src::D,dest::D,
ilabel, olabel, w=one(W)) where {W,D<:Integer,A<:Arc{W,D}}
if max(src,dest) - length(fst) > 0
add_states!(fst, max(src,dest) - length(fst) ) # eventually expand states
end
i = parse_label(ilabel, fst.isym)
o = parse_label(olabel, fst.osym)
arc = Arc{W,D}(i,o,W(w),dest)
push_arc!(fst, src, arc)
return fst
end
# Note that this avoids checking if symbol is already present in the fst
function push_arc!(fst::WFST{W,A,D}, src::D, arc::A) where {W,A,D}
s = get_states(fst)
push!(s[src], arc)
return fst
end
count_arcs(fst::WFST) = isempty(get_states(fst)) ? 0 : sum(length(s) for s in get_states(fst))
Base.getindex(fst::WFST, i) = getindex(get_states(fst),i)
Base.iterate(fst::WFST, args...) = iterate(get_states(fst), args...)
Base.isempty(fst::WFST) = isempty(get_states(fst))
struct ArcIterator
fst::WFST
end
function Base.iterate(iter::ArcIterator, it_st=(1,1))
i, j = it_st # state id, arc id
s = get_states(iter.fst)[i]
if j > length(s)
while true
i += 1 # next state
if i > length(iter.fst) return nothing; end
s = get_states(iter.fst)[i]
if !isempty(s) break; end
end
j = 1 # reinit arc
end
return s[j], (i,j+1)
end
Base.length(iter::ArcIterator) = count_arcs(iter.fst)
export get_arcs
"""
`get_arcs(fst::WFST) = ArcIterator(fst)`
Returns an iterator that can be used to loop through all of the arcs of `fst`.
"""
get_arcs(fst::WFST) = ArcIterator(fst)
export get_weight
"""
`get_weight(fst::WFST,i)`
Returns the weight of the `i`-th state of `fst`. If there is no weight `nothing` is returned.
"""
function get_weight(fst::WFST,i)
if isinitial(fst,i)
return get_initial_weight(fst,i)
elseif isfinal(fst,i)
return get_final_weight(fst,i)
else
return nothing
end
end
# arc inspectors
function get_ilabel(fst::WFST{W,A,D},s::D,a::D) where {W,A,D}
return get_iisym(fst)[get_ilabel(fst[s][a])]
end
function get_olabel(fst::WFST{W,A,D},s::D,a::D) where {W,A,D}
return get_iosym(fst)[get_olabel(fst[s][a])]
end
function (fst::WFST{W,A,D,I,O})(labels::Vector{I}) where {W,A,D,I,O}
i = get_initial(fst)
w = get_initial_weight(fst,i)
olabels = Vector{O}()
isym = get_isym(fst)
osym = get_iosym(fst)
cnt = 1
while cnt <= length(labels)
n = 0
lab = labels[cnt]
if iseps(lab)
cnt += 1
else
for arc in fst[i]
ilab = get_ilabel(arc)
if ilab == isym[lab] || iseps(ilab)
if !iseps(ilab)
cnt += 1
end
olab = get_olabel(arc)
if !iseps(olab)
push!(olabels,osym[olab])
end
n = get_nextstate(arc)
w *= get_weight(arc)
break
end
end
if n == 0 # there is no state with lab
w = zero(W)
break
else
i = n
end
end
end
# finished labels but there could still be ilab == ϵ
while !isfinal(fst,i)
n = 0
for arc in fst[i]
ilab = get_ilabel(arc)
olab = get_olabel(arc)
if iseps(ilab)
if !iseps(olab)
push!(olabels,osym[olab])
end
n = get_nextstate(arc)
w *= get_weight(arc)
break
end
end
if n == 0 # there is no state with lab
w = zero(W)
break
else
i = n
end
end
if isfinal(fst,i)
w *= get_final_weight(fst,i)
else
w = zero(W)
end
return olabels, w
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1561 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export get_paths, collectpaths
struct PathIterator{W,A,D,F}
bfs::BFS{W,A,D,F}
end
"""
`get_paths(fst::FST, [i = get_initial(fst;single=true)])`
Returns an iterator that generates all of the possible paths of `fst` starting from `i`.
Notice that the `fst` must be acyclic for the algorithm to stop (see [`is_acyclic`](@ref)).
"""
get_paths(fst::WFST, i=get_initial(fst;single=true)) = PathIterator(BFS(fst,i))
function Base.iterate(it::PathIterator, q=init_bfs(it.bfs.fst, it.bfs.initial))
if isempty(q)
return nothing
else
while true
(i,p), q = iterate(it.bfs,q)
if isfinal(it.bfs.fst,i)
w = get_final_weight(it.bfs.fst,i)
pf = update_weight(p,w)
return pf, q
end
end
end
end
"""
`collectpaths(fst::FST, [i = get_initial(fst;first=true)])`
Returns an array containing all of the possible paths of `fst` starting from `i`.
Notice that the `fst` must be acyclic for the algorithm to stop (see [`is_acyclic`](@ref)).
"""
function collectpaths(fst::WFST{W,A,D,I,O},
i::D=get_initial(fst;single=true)) where {W,D,I,O,
A <: Arc{W,D}}
paths = Vector{Path{W,D}}()
if !isempty(fst)
pathsIt = BFS(fst, i)
for (i,p) in pathsIt
if isfinal(fst,i)
w = get_final_weight(fst,i)
pf = update_weight(p,w)
push!(paths,pf)
end
end
end
return paths
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 2369 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export arcmap
"""
`arcmap(f::Function, fst::WFST, args...; modify_initials=identity, modify_finals=identity, isym=get_isym(fst), osym=get_osym(fst))`
Creates a new WFST from `fst` by applying the function `f` to all its arcs, see [`Arc`](@ref).
The arguments of `f` can be specified in `args`.
The functions `modify_initials` and `modify_finals` operate in the initial and final dictionaries, which keys are the initial/final states and values are the corresponding state weights.
Input and output tables can also be modified using the keywords `isym` and `osym`.
The following example shows how to use `arcmap` to convert the type of weight of a WFST:
```julia
julia> A = WFST(["a","b","c"]); # by default weight is TropicalWeight{Float32}
julia> add_arc!(A,1=>2,"a"=>"a",1);
julia> add_arc!(A,1=>3,"b"=>"c",3);
julia> initial!(A,1); final!(A,2,4); final!(A,3,2)
WFST #states: 3, #arcs: 2, #isym: 3, #osym: 3
|1/0.0f0|
a:a/3.0f0 → (2)
b:c/3.0f0 → (3)
((2/4.0f0))
((3/2.0f0))
julia> trop2prob(x) = ProbabilityWeight{Float64}(exp(-get(x)))
trop2prob (generic function with 1 method)
julia> function trop2prob(arc::Arc)
ilab = get_ilabel(arc)
olab = get_olabel(arc)
w = trop2prob(get_weight(arc))
n = get_nextstate(arc)
return Arc(ilab,olab,w,n)
end
trop2prob (generic function with 2 methods)
julia> trop2prob(initials::Dict) = Dict(i => trop2prob(w) for (i,w) in initials)
trop2prob (generic function with 3 methods)
julia> arcmap(trop2prob,A; modify_initials=trop2prob, modify_finals=trop2prob)
WFST #states: 3, #arcs: 2, #isym: 3, #osym: 3
|1/1.0|
a:a/0.3678794503211975 → (2)
b:c/0.049787066876888275 → (3)
((2/0.018315639346837997))
((3/0.1353352814912796))
```
"""
function arcmap(f::Function, fst::WFST, args...;
modify_initials = identity,
modify_finals = identity,
isym = get_isym(fst),
osym = get_osym(fst)
)
states = [f.(arcs, args...) for arcs in get_states(fst)]
finals = modify_finals( deepcopy(fst.finals) )
initials = modify_initials(deepcopy(fst.initials))
osym = deepcopy(fst.osym)
isym = deepcopy(fst.isym)
pfst = WFST(states,initials,finals,isym,osym)
return pfst
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 2281 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
import Base:*
"""
`*(A::WFST,B::WFST)`
Returns `C`, the concatenation/product of `A` and `B`. If `A` converts the sequence `a_i` to `a_o` with weight `wa` and `B` converts the sequence `b_i` to `b_o` with weight `wb` then C` converts the sequence `[a_i,b_i]` to `[a_o,b_o]` with weight `wa*wb`.
```julia
julia> sym = ["a","b","c","d","α","β","γ","δ"];
julia> A = WFST(sym);
julia> add_arc!(A,1=>2,"a"=>"α");
julia> add_arc!(A,2=>3,"b"=>"β");
julia> initial!(A,1); final!(A,3,5)
WFST #states: 3, #arcs: 2, #isym: 8, #osym: 8
|1/0.0f0|
a:α/0.0f0 → (2)
(2)
b:β/0.0f0 → (3)
((3/5.0f0))
julia> B = WFST(sym);
julia> add_arc!(B,1=>2,"c"=>"γ");
julia> add_arc!(B,2=>3,"d"=>"δ");
julia> initial!(B,1); final!(B,3,2)
WFST #states: 3, #arcs: 2, #isym: 8, #osym: 8
|1/0.0f0|
c:γ/0.0f0 → (2)
(2)
d:δ/0.0f0 → (3)
((3/2.0f0))
julia> C = A*B
WFST #states: 6, #arcs: 5, #isym: 8, #osym: 8
|1/0.0f0|
a:α/0.0f0 → (2)
(2)
b:β/0.0f0 → (3)
(3)
ϵ:ϵ/5.0f0 → (4)
(4)
c:γ/0.0f0 → (5)
(5)
d:δ/0.0f0 → (6)
((6/2.0f0))
julia> A(["a","b"])
(["α", "β"], 5.0f0)
julia> B(["c","d"])
(["γ", "δ"], 2.0f0)
julia> C(["a","b","c","d"])
(["α", "β", "γ", "δ"], 7.0f0)
```
"""
function *(A::WFST,B::WFST)
isym = get_isym(A)
osym = get_osym(A)
W = typeofweight(A)
if isym != get_isym(B)
throw(ErrorException("WFSTs have different input symbol tables"))
end
if osym != get_osym(B)
throw(ErrorException("WFSTs have different output symbol tables"))
end
if W != typeofweight(B)
throw(ErrorException("WFSTs have different type of weigths $W and $(typeofweight(B))"))
end
C = deepcopy(A)
offset = length(C)
add_states!(C,length(B))
for (q,arcs) in enumerate(get_states(B))
for arc in arcs
ilab, olab = get_ilabel(arc), get_olabel(arc)
w, n = get_weight(arc), get_nextstate(arc)
push!(C[q+offset],Arc(ilab,olab,w,n+offset))
end
end
final_A = get_final(A; single=false)
initial_B = get_initial(B; single=false)
for (qf,wf) in final_A
for (qi,wi) in initial_B
push!(C[qf],Arc(0,0,wf*wi,qi+offset))
end
rm_final!(C,qf)
end
for (q,w) in get_final(B; single=false)
final!(C,q+offset,w)
end
return C
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1405 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export closure!
"""
`closure!(fst; star=true)`
Same as `closure` but modifies `fst` in-place.
"""
function closure!(fst; star=true)
if star
fst = closure_star!(fst)
else
fst = closure_plus!(fst)
end
return fst
end
export closure
"""
`closure(fst; star=true)`
Returns a new WFST `cfst` that is the closure of `fst`.
If `fst` transuces `labels` to `olabel` with weight `w`, `cfst` will be able to transduce `repeat(ilabels,n)` to `repeat(olabels,m)` with weight `w^n` for any integer `n`.
If `star` is `true`, `cfst` will transduce the empty string to itself with weight one.
"""
function closure(fst; star=true)
fst_copy = deepcopy(fst)
closure!(fst_copy; star=star)
return fst_copy
end
function closure_plus!(fst::WFST{W,A,D,I,O}) where {W,A,D,I,O}
ϵi, ϵo = get_eps(I), get_eps(O)
i = get_initial(fst; single=true)
for k in keys(get_final(fst; single=false))
w = get_final_weight(fst,k)
add_arc!(fst,k,i,ϵi,ϵo,w)
end
return fst
end
function closure_star!(fst::WFST{W,A,D,I,O}) where {W,A,D,I,O}
ϵi, ϵo = get_eps(I), get_eps(O)
closure_plus!(fst)
i = get_initial(fst,single=true)
w = get_initial_weight(fst,i)
rm_initial!(fst,i)
ni = size(fst,1)+1
add_arc!(fst,ni,i,ϵi,ϵo,w)
initial!(fst,ni)
final!(fst,ni)
return fst
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 2713 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
import Base: ∘
"""
`∘(A::WFST,B::WFST; filter=EpsSeq, connect=true)`
Perform composition of the transucers `A` and `B`.
The keyword `filter` can specify the composition filter to be used.
If `connect` is set to `true` after completing the composition the [`connect`](@ref) algorithm is applied.
See [Allauzen et al. "Filters for Efficient Composition of Weighted Finite-State Transducers"](https://doi.org/10.1007/978-3-642-18098-9_4)
"""
function ∘(A::WFST{W1,A1,D,I1,O1}, B::WFST{W2,A2,D,I2,O2};
filter=EpsSeq, connect=true
) where {W1, W2, D, I1, I2, O1, O2,
A1 <: Arc{W1,D},
A2 <: Arc{W2,D}}
if O1 != I2
error("Output label of A must be of the same type of input labels of B.")
end
if W1 != W2
error("Weights of A must be of the same type of weights of B.")
end
if !(A.osym === B.isym)
if A.osym != B.isym # construncting A and B using the same object avoids this check
throw(ErrorException("Output symbol table of A not consistent with input symbol table of B."))
end
end
function updateC!(it::ComposeIterator,
i::D,q1::D,q2::D,q3::D,w3::W,
e1::Arc{W,D},e2::Arc{W,D},
src::D,dest::D) where {W,A,D}
wc = get_weight(e1)*get_weight(e2)
if max(src,dest) - length(it.C) > 0
add_states!(it.C, max(src,dest) - length(it.C) ) # eventually expand states
end
push_arc!(it.C,src,Arc(get_ilabel(e1),get_olabel(e2),wc,dest))
end
function updateCfinal!(it::ComposeIterator,
i::D,q1::D,q2::D,q3::D,w3::W,
src::D) where {W,A,D}
if isinitial(it.A,q1) && isinitial(it.B,q2)
w1, w2 = get_initial_weight(it.A,q1), get_initial_weight(it.B,q2)
initial!(it.C, src, w1*w2)
end
if isfinal(it.A,q1) && isfinal(it.B,q2) &&
q3 <= it.filter.q_max && w3 != zero(typeof(w3))
w1, w2 = get_final_weight(it.A,q1), get_final_weight(it.B,q2)
final!(it.C, src, w1*w2*w3)
end
end
ϵ = 0
ϵL = max(length(get_osym(A)),length(get_isym(B)))+1
f = filter{W1,D}(ϵL)
# add self loops
for i in 1:size(A,1)
push_arc!(A,i,Arc{W1,D}(ϵ,ϵL,one(W1),i))
end
for i in 1:size(B,1)
push_arc!(B,i,Arc{W1,D}(ϵL,ϵ,one(W1),i))
end
C = WFST(get_isym(A),get_osym(B); W = W1)
z = ComposeIterator(A,B,C,f,updateC!,updateCfinal!)
for zi in z
nothing
end
# delete self loops
for s in get_states(A) deleteat!(s,length(s)) end
for s in get_states(B) deleteat!(s,length(s)) end
if connect
connect!(C)
end
return C
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 2568 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
# using filters from paper
# Allauzen et al. Filters for Efficient Composition of Weighted Finite-State Transducers
# main differences here are that we use ⟂ = 0 and base 1 index for the states
abstract type CompositionFilter end
export Trivial
"""
`Trivial`
Simplest composition filter, can be used for epsilon-free WFSTs.
"""
struct Trivial{W,D} <: CompositionFilter
i3::D
q_max::D
rho::Vector{W}
ϵL::D
Trivial{W,D}(ϵL::D) where {W,D} = new{W,D}(1,2,[one(W),one(W)],ϵL)
end
function phi(filter::Trivial, e1, e2, q3)
ϵL = filter.ϵL
o_e1, i_e2 = get_olabel(e1), get_ilabel(e2)
if (o_e1 == i_e2) ||
(o_e1 == ϵL && i_e2 == 0) ||
(o_e1 == 0 && i_e2 == ϵL)
if iseps(get_ilabel(e1)) && iseps(get_olabel(e2))
# avoids self eps:eps loops
return e1, e2, 0
else
return e1, e2, 1
end
else
return e1, e2, 0
end
end
export EpsMatch
"""
`EpsMatch`
Can be used for WFSTs containing epsilon labels.
Avoids redundant epsilon paths and giving priority to those that match epsilon labels.
"""
struct EpsMatch{W,D} <: CompositionFilter
i3::D
q_max::D
rho::Vector{W}
ϵL::D
EpsMatch{W,D}(ϵL::D) where {W,D} =
new{W,D}(1,3,[one(W),one(W),one(W)],ϵL)
end
function phi(filter::EpsMatch, e1, e2, q3)
ϵL = filter.ϵL
o_e1, i_e2 = get_olabel(e1), get_ilabel(e2)
if (o_e1 == i_e2) &&
!(iseps(o_e1) || o_e1 == ϵL) &&
!(iseps(i_e2) || i_e2 == ϵL)
return e1, e2, 1
elseif (o_e1 == 0) && (i_e2 == 0) && (q3 == 1)
return e1, e2, 1
elseif (o_e1 == ϵL) && (i_e2 == 0) && (q3 != 3)
return e1, e2, 2
elseif (o_e1 == 0) && (i_e2 == ϵL) && (q3 != 2)
return e1, e2, 3
else
return e1, e2, 0
end
end
export EpsSeq
"""
`EpsSeq`
Can be used for WFSTs containing epsilon labels.
Avoids redundant epsilon paths.
Gives priority to epsilon paths consisting of epsilon-arcs in `A` followed by epsilon-arcs in `B`.
"""
struct EpsSeq{W,D} <: CompositionFilter
i3::D
q_max::D
rho::Vector{W}
ϵL::D
EpsSeq{W,D}(ϵL::D) where {W,D} =
new{W,D}(1,2,[one(W),one(W)],ϵL::D)
end
function phi(filter::EpsSeq, e1, e2, q3)
ϵL = filter.ϵL
o_e1, i_e2 = get_olabel(e1), get_ilabel(e2)
if (o_e1 == i_e2) &&
!(iseps(o_e1) || o_e1 == ϵL) &&
!(iseps(i_e2) || i_e2 == ϵL)
return e1, e2, 1
elseif (o_e1 == 0) && (i_e2 == ϵL) && (q3 == 1)
return e1, e2, 1
elseif (o_e1 == ϵL) && (i_e2 == 0)
return e1, e2, 2
else
return e1, e2, 0
end
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 753 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export connect!
"""
`connect!(fst::WFST, [i = get_initial(fst,single=true)])`
Same as `connect` but modifies `fst` in-place.
"""
function connect!(fst::WFST, i = get_initial(fst,single=true))
if !isempty(fst)
scc, c, v = get_scc(fst,i)
idxs = findall( (|).((!).(v),(!).(c)) )
return rm_state!(fst,idxs)
else
return fst
end
end
export connect
"""
`connect(fst::WFST, [i = get_initial(fst,single=true)])`
Remove states that do not belong to paths that end in final states when starting from `i`.
"""
function connect(fst::WFST, args...)
fst_copy = deepcopy(fst)
connect!(fst_copy, args...)
return fst_copy
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 2852 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export determinize_fsa
"""
`determinize_fsa(fsa)`
Returns a deterministic finite state acceptor. `fsa` must be an acceptor ([`is_acceptor`](@ref)).
Requires the WFST to be defined in a left distributive and weakly divisible semiring.
See [M. Mohri, F. Pereira, Fernando, M. Riley, Michael "Speech Recognition with Weighted Finite-State Transducers" in Springer Handb. Speech Process. 2008](https://cs.nyu.edu/~mohri/pub/hbka.pdf) for details.
"""
function determinize_fsa(fst::WFST{W,A,D,I,O}) where {W,A,D,I,O}
if !isleft(W)
throw(ErrorException("Semiring $W is not left distributive, fst cannot be determinized."))
end
if !isweaklydivisible(W)
throw(ErrorException("Semiring $W is not weakly divisible, fst cannot be determinized."))
end
dfst = WFST(get_isym(fst), get_osym(fst); W = W)
i = get_initial(fst)
w = get_initial_weight(fst,i)
initial!(dfst,get_initial(fst))
S = Queue{Set{Tuple{D,W}}}()
qq = Set([(i,w)])
cnt = 1
qq2state = Dict( qq => cnt ) # new states
enqueue!(S,qq)
while !isempty(S)
pp = dequeue!(S)
lab2weight = Dict{D,W}() # set in line 8 of Fig.10 in [1]
lab_nextstate2weight = Dict{D,Dict{D,W}}() # set in line 9 of Fig.10 in [1]
for (p,v) in pp
for arc in fst[p]
lab, w, n = get_ilabel(arc), get_weight(arc), get_nextstate(arc)
vw = v*w
if get_ilabel(arc) in keys(lab2weight)
lab2weight[lab] += vw
else
lab2weight[lab] = vw
end
if lab in keys(lab_nextstate2weight)
if n in keys(lab_nextstate2weight[lab])
lab_nextstate2weight[lab][n] += vw
else
lab_nextstate2weight[lab][n] = vw
end
else
lab_nextstate2weight[lab] = Dict(n => vw)
end
end
end
for lab in keys(lab2weight)
qq = Set{Tuple{D,W}}()
wp = lab2weight[lab]
for n in keys(lab_nextstate2weight[lab])
vw = lab_nextstate2weight[lab][n]
push!(qq,(n, one(W) / wp * vw))
end
if !(qq in keys(qq2state))
cnt += 1
qq2state[qq] = cnt
src, dest = qq2state[pp], cnt
if max(src,dest) - length(dfst) > 0
add_states!(dfst, max(src,dest) - length(dfst) ) # expand states
end
push!(dfst[src],Arc{W,D}(lab,lab,wp,dest))
rho = zero(W)
any_final = false
for (n,v) in qq
if isfinal(fst,n)
any_final = true
rho += v*get_final_weight(fst,n)
end
end
if any_final final!(dfst,cnt,rho) end
enqueue!(S,qq)
else
src, dest = qq2state[pp], qq2state[qq]
push!(dfst[src],Arc{W,D}(lab,lab,wp,dest))
end
end
end
return dfst
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 2129 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export get_scc
"""
`get_scc(fst::WFST, i = get_initial(fst;single=true); filter=arc->true)`
Calculates the strongly connected components of 'fst' using Tarjan's algorithm.
Returns a tuple `(scc,c,v)`:
* `scc` are the strongly connected components of `fst`
* `c` is a boolean array containing the accessibility form the `i`
* `v` are the visited states of the `fst`
The function `filter` can be used to consider only arcs with specific properties.
"""
function get_scc(fst::WFST, i = get_initial(fst;single=true); kwargs...)
if isempty(fst)
return Bool[]
else
stack=Int[]
sccs=Vector{Vector{Int}}()
lowlink=zeros(Int,size(fst,1))
order=zeros(Int,size(fst,1))
onstack=zeros(Bool,size(fst,1))
coaccess=zeros(Bool,size(fst,1))
dfs = DFS(fst,i; kwargs...)
cnt = 1
lowlink[1] = cnt
order[1] = cnt
onstack[1] = true
push!(stack,i)
for (p,s,n,d,e,a) in dfs
if d # discovering new nodes
cnt +=1
lowlink[n] = cnt
order[n] = cnt
onstack[n] = true
push!(stack,n)
else
if e # state explored
if isfinal(fst,s)
coaccess[s] = true
end
if lowlink[s] == order[s]
scc = Vector{Int}()
c_coaccess = false
a = 0
while a != s
a = pop!(stack)
onstack[a] = false
if coaccess[a] c_coaccess = true end
push!(scc,a)
end
if c_coaccess
for z in scc coaccess[s] = true end
end
reverse!(scc)
push!(sccs,scc)
end
if p != 0
lowlink[p] = min(lowlink[p],lowlink[s])
if coaccess[s] coaccess[p] = true end
end
else
# n already visited
lowlink[s] = min(order[n],lowlink[s])
if coaccess[n] coaccess[s] = true end
end
end
end
reverse!(sccs)
return sccs, coaccess, dfs.is_visited
end
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 352 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
"""
`inv(fst::WFST)`
Inverts `fst` such that input labels are swaped with output labels.
"""
function Base.inv(fst::WFST)
ifst = arcmap(inv, fst)
ifst = WFST(ifst.states,ifst.initials,ifst.finals,ifst.osym,ifst.isym)
return ifst
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 494 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export is_visited
"""
`is_visited(fst::WFST, i = get_initial(fst;single=true))`
Return an array of booleans indicating if the i-th state of the fst is visted starting form `i`.
"""
function is_visited(fst::WFST, i = get_initial(fst;single=true))
if isempty(fst)
return Bool[]
else
d = DFS(fst,i)
for i in d
nothing
end
return d.is_visited
end
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 871 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
function permute_states(fst::WFST{W,A,D},perm::Vector{D}) where {W,A,D,I}
if length(perm) != length(fst)
throw(ErrorException("Number of states of WFST $(lenth(fst)) not equal to permutation length $(length(perm))"))
end
isym=get_isym(fst)
osym=get_osym(fst)
iperm = invperm(perm)
initials = Dict(iperm[k] => fst.initials[k] for k in keys(fst.initials))
finals = Dict(iperm[k] => fst.finals[k] for k in keys(fst.finals))
states = [Vector{A}() for i in 1:size(fst,1)]
for (j,i) in enumerate(perm)
for arc in fst[i]
push!(states[j],
Arc{W,D}(get_ilabel(arc),get_olabel(arc),
get_weight(arc),iperm[get_nextstate(arc)])
)
end
end
return WFST(states,initials,finals,isym,osym)
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 768 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export proj
"""
`proj(iolabel::Function, fst::WFST)`
Projects input labels to output labels (or viceversa).
The function `get_iolabel` should either be the function `get_ilabel` or `get_olabel`.
"""
function proj(get_iolabel::Function, fst::WFST)
if !( (get_iolabel == get_ilabel) || (get_iolabel == get_olabel) )
throw(ErrorException("Input function should be either `ilabel` or `olabel`."))
end
pfst = arcmap(proj, fst, get_iolabel)
if get_iolabel == get_ilabel
pfst = WFST(pfst.states,pfst.initials,pfst.finals,pfst.isym,pfst.isym)
else
pfst = WFST(pfst.states,pfst.initials,pfst.finals,pfst.osym,pfst.osym)
end
return pfst
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1101 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
import Base:reverse
"""
`reverse(fst::WFST)`
Returns `rfst`, the reversed version of `fst`.
If `fst` transuces the sequence `x` to `y` with weight `w`, `rfst` transuces the reverse of `x` to the reverse of `y` with weight `reverse(w)`.
"""
function reverse(fst::WFST{W,A,D}) where {W,A,D}
RW = FiniteStateTransducers.reversetype(W)
rfst = WFST(get_isym(fst),get_osym(fst); W = RW)
add_states!(rfst,length(fst)+1)
initial!(rfst,D(1)) # 1 is an additional initial superstate
for (q,arcs) in enumerate(get_states(fst))
qr = D(q+1) # reversed state
if isinitial(fst,q)
w = get_weight(fst,q)
final!(rfst,qr,reverse(w))
end
if isfinal(fst,q)
w = get_weight(fst,q)
push!(rfst[1], Arc{RW,D}(D(0),D(0),reverse(w),qr))
end
for arc in arcs
n = get_nextstate(arc)+1
w = get_weight(arc)
ilab, olab= get_ilabel(arc), get_olabel(arc)
push!(rfst[n], Arc{RW,D}(ilab,olab,reverse(w),qr))
end
end
return rfst
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1834 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export rm_eps!
# follows M. MOHRI GENERIC ∊-REMOVAL AND INPUT∊-NORMALIZATION ALGORITHMS FOR WEIGHTED TRANSDUCERS
# many optimizations are currently missing
"""
`rm_eps!(fst::WFST)`
Same as `rm_eps` but operates in place.
"""
function rm_eps!(fst::WFST{W,A,D}) where {W,A,D}
iseps_arc = arc -> iseps(get_ilabel(arc)) && iseps(get_olabel(arc))
for (p,s) in enumerate(get_states(fst))
arcs_to_rm = D[]
new_arcs = Tuple{D,Arc{W,D}}[]
for (i,arc) in enumerate(s)
if iseps_arc(arc)
push!(arcs_to_rm,i)
end
# get closure on Aϵ
C = shortest_distance(fst,p; filter=iseps_arc)
# TODO this allocate stuff... would make sense that C is also sparse?
for (q,w) in enumerate(C)
if w != zero(W)
for a in fst[q]
if !iseps_arc(a)
new_arc=Arc{W,D}(
get_ilabel(a),
get_olabel(a),
get_weight(a) * w,
get_nextstate(a)
)
push!(new_arcs, (p,new_arc))
end
end
if isfinal(fst,q)
if !isfinal(fst,p)
final!(fst,p,zero(W))
end
fst.finals[p] += w * fst.finals[q]
end
end
end
end
deleteat!(s,arcs_to_rm)
for (p,a) in new_arcs
push_arc!(fst,p,a)
end
unique!(fst[p]) # avoids multiple arcs with same i/o
end
connect!(fst)
return fst
end
export rm_eps
"""
`rm_eps(fst::WFST)`
Returns an equivalent WFST where arcs with input and output labels are removed.
"""
function rm_eps(fst::WFST)
new_fst = deepcopy(fst)
rm_eps!(new_fst)
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1232 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export rm_state!
function rm_state!(fst::WFST, idx)
# map to new indices with (-1) where rm
new_id = zeros(Int,length(fst))
s = get_states(fst)
for i in idx
new_id[i] = -1
rm_initial!(fst,i)
rm_final!(fst,i)
end
nstates = 0
# this pushes all states to be removed at the end of s
for i in eachindex(s)
if new_id[i] != -1
nstates += 1
new_id[i] = nstates
if isfinal(fst,i)
w = get_final_weight(fst,i)
rm_final!(fst,i)
final!(fst,nstates,w)
end
if isinitial(fst,i)
w = get_initial_weight(fst,i)
rm_initial!(fst,i)
initial!(fst,nstates,w)
end
if i != nstates
s[i], s[nstates] = s[nstates], s[i]
end
end
end
# remove states
deleteat!(s,(length(s)-length(idx)+1):length(s))
# remove arcs and update idx
for si in s
to_rm = Int[]
for (ii, arc) in enumerate(si)
t = new_id[get_nextstate(arc)]
if t != -1
new_arc = change_next(arc,t)
si[ii] = new_arc
else
push!(to_rm,ii)
end
end
deleteat!(si,to_rm)
end
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 2537 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export shortest_distance
"""
`shortest_distance(fst[, s=get_initial(fst); filter=arc->true, reverse=false)`
Computes the shortest distance between the state `s` to every other state.
The shortest distance between `s` and `i` is defined as the sum of the weights of all paths between these states.
Weights are required to be rigth distributive and k-closed.
If `fst` has `N` states a `N`-long vector is returned where the `i`-the element contains the shortest distance between the states `s` and `i`.
If `reversed==true` the shortest distance from the final states is computed.
In this case `s` has no effect since a new initial superstate is added to the reversed WFST.
Here weights are required to be left distributive and k-closed.
See Mohri "Semiring framework and algorithms for shortest-distance problems", Journal of Automata, Languages and Combinatorics 7(3): 321-350, 2002.
"""
function shortest_distance(fst::WFST{W}, s=get_initial(fst); filter=arc->true, reversed=false) where {W}
if reversed
if !isright(W)
throw(ErrorException("Weight $W is not right distributive"))
end
if !ispath(W)
throw(ErrorException("Weight $W must satisfy the \"path\" property"))
end
rfst = reverse(fst)
d = no_check_shortest_distance(rfst,get_initial(rfst);filter=filter)
return d[2:end]
else
if !isleft(W)
throw(ErrorException("Weight $W is not left distributive"))
end
if !ispath(W)
throw(ErrorException("Weight $W must satisfy the \"path\" property"))
end
return no_check_shortest_distance(fst,s;filter=filter)
end
end
function no_check_shortest_distance(fst::WFST{W,A,D},
s::D=get_initial(fst);
filter=arc->true) where {W,A,D}
Ns = size(fst,1)
d = zeros(W,Ns) # d[q] estimate of shortest distance between q and s
r = zeros(W,Ns) # r[q] total weight added to d[q] since last time q was extracted from S
d[s], r[s] = one(W), one(W)
S = Queue{D}()
enqueue!(S,s)
while !isempty(S)
q = dequeue!(S)
R = r[q]
r[q] = zero(W)
for arc in fst[q]
if filter(arc)
n, w = get_nextstate(arc), get_weight(arc)
dn = d[n]
if dn != (dn+(R*w))
d[n] = dn+(R*w)
r[n] = r[n]+(R*w)
if !(n in S)
enqueue!(S,n)
end
end
end
end
end
d[s] = one(W)
return d
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1383 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export topsortperm
"""
`topsortperm(fst::WFST, i = get_initial(fst); filter=arc->true)`
Requires `fst` to be acyclic.
Returns the topological permutation of states of `fst` starting from the `i`-th state.
Modify the `filter` function to perform the operation considering only specific arcs.
"""
function topsortperm(fst::WFST, i = get_initial(fst;single=true); kwargs...)
if isempty(fst)
return Bool[]
else
perm=zeros(Int,size(fst,1))
acyclic=true
perm[1] = i
cnt = 2
dfs = DFS(fst,i; kwargs...)
for (p,s,n,d,e,a) in dfs
if d # discovering new nodes
perm[cnt] = n
cnt += 1
else
if !e && !dfs.is_completed[n]
throw(ErrorException("Topological sort failed, fst is not acyclic"))
end
end
end
return perm
end
end
export topsort
"""
`topsort(fst::WFST, i = get_initial(fst); filter=arc->true)`
Requires `fst` to be acyclic.
Returns an equivalent WFST to `fst` which is topologically sorted starting from the `i`-th state.
Modify the `filter` function to perform the operation considering only specific arcs.
"""
function topsort(fst::WFST, i = get_initial(fst;single=true); kwargs...)
perm = topsortperm(fst,i;kwargs...)
return permute_states(fst,perm)
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 2232 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export wfst2tr
"""
`wfst2tr(fst,Nt; get_label=get_ilabel)`
Returns an array `time2tr` of length `Nt-1`.
The `t`-th element of `time2tr` is a dictionary mapping the transition index between input label at time `t` to the input label at time `t+1`.
```julia
julia> using FiniteStateTransducers
julia> H = WFST(["a1","a2","a3"],["a"]);
julia> add_arc!(H,1,2,"a1","a");
julia> add_arc!(H,2,3,"a2","<eps>");
julia> add_arc!(H,2,2,"a2","<eps>");
julia> add_arc!(H,3,4,"a3","<eps>");
julia> add_arc!(H,3,2,"a3","a");
julia> initial!(H,1);
julia> final!(H,4)
WFST #states: 4, #arcs: 5, #isym: 3, #osym: 1
|1/0.0f0|
a1:a/0.0f0 → (2)
(2)
a2:ϵ/0.0f0 → (3)
a2:ϵ/0.0f0 → (2)
(3)
a3:ϵ/0.0f0 → (4)
a3:a/0.0f0 → (2)
((4/0.0f0))
julia> Nt = 10;
julia> time2tr = wfst2tr(H,Nt)
9-element Array{Dict{Int64,Array{Int64,1}},1}:
Dict(1 => [2])
Dict(2 => [2, 3])
Dict(2 => [2, 3],3 => [2])
Dict(2 => [2, 3],3 => [2])
Dict(2 => [2, 3],3 => [2])
Dict(2 => [2, 3],3 => [2])
Dict(2 => [2, 3],3 => [2])
Dict(2 => [2],3 => [2])
Dict(2 => [3])
```
"""
function wfst2tr(fst::WFST{W,A,D},Nt; get_label=get_ilabel) where {W,A,D}
isym=get_isym(fst)
Ns = length(isym)
X = matrix2wfst(isym,ones(W,Ns,Nt); W = W)
Z = ∘(X,fst; connect=true)
i = get_initial(Z)
current_states = Set{D}([i])
next_states = Set{D}()
time2transitions = [Dict{D,Vector{D}}() for t in 1:Nt-1]
t = 1
while !isempty(current_states)
dict = Dict{D,Set{D}}()
for c in current_states
for c_arc in Z[c]
src = D(get_label(c_arc))
n = get_nextstate(c_arc)
push!(next_states,n)
dest = Set{D}([D(get_label(n_arc)) for n_arc in Z[n]])
if !isempty(dest)
if haskey(dict,src)
union!(dict[src],dest)
else
dict[src] = dest
end
end
end
end
if t < Nt
time2transitions[t] = Dict(k=>[dict[k]...] for k in keys(dict))
else
if !isempty(dict)
error("something is wrong with the graph")
end
end
t += 1
current_states, next_states = next_states, Set{D}()
end
return time2transitions
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1268 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
# Breadth-first search
export BFS
"""
`BFS(fst,initial)`
Returns an iterator that performs a breadth-first search (BFS) of `fst` starting from the state `initial`.
At each iteartion the tuple `(i,p)` is returned, where `i` is the current state and `p` a [`Path`](@ref).
"""
struct BFS{W,A,D,F <: WFST{W,A,D}}
fst::F
initial::D
function BFS(fst::F,initial::D) where {W,A,D,F <: WFST{W,A,D}}
if initial==0
throw(ErrorException("Invalid initial state"))
end
new{W,A,D,F}(fst,initial)
end
end
function init_bfs(fst::WFST{W,A,D}, initial::D) where {W,D,A<:Arc{W,D}}
q = Queue{Tuple{D,Path{W,D}}}()
isym = get_isym(fst)
osym = get_osym(fst)
w = get_initial_weight(fst,initial)
p = Path(Vector{D}(), Vector{D}(), w, isym, osym)
enqueue!(q, (initial, p))
return q
end
function Base.iterate(it::BFS,
q = init_bfs(it.fst,it.initial))
if isempty(q)
return nothing
else
i, p = dequeue!(q)
s = it.fst[i]
for arc in s
p_new = update_path(p, get_ilabel(arc), get_olabel(arc), get_weight(arc))
enqueue!(q, (get_nextstate(arc), p_new))
end
return (i,p), q
end
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 2136 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
struct ComposeIterator{D<:Integer,
F1<:WFST,
F2<:WFST,
F3,
CF
}
A::F1
B::F2
C::F3 # this can be anything you need to build (e.g. a WFST)
filter::CF # composition filter
updateC!::Function # modify C in place
updateCfinal!::Function # modify C in place (after all arcs)
function ComposeIterator(A::F1,
B::F2,
C::F3,
filter::CF,
updateC!,
updateCfinal!
) where {D,W,I,O,O2,
A1 <: Arc{W,D},
F1 <: WFST{W,A1,D,I,O},
F2 <: WFST{W,A1,D,O,O2},
F3,
CF
}
new{D,F1,F2,F3,CF}(A,B,C,filter,updateC!,updateCfinal!)
end
end
function init(it::ComposeIterator{D}) where {D}
Q = Dict{Tuple{D,D,D},D}()
S = Queue{Tuple{D,D,D}}()
i1 = get_initial(it.A, single=true)
i2 = get_initial(it.B, single=true)
src = 1 #new state for C
i3 = it.filter.i3
push!(Q, (i1,i2,i3) => src)
enqueue!(S,(i1,i2,i3))
return Q, S, src
end
function Base.iterate(it::ComposeIterator, it_st=init(it))
Q, S, i = it_st
if isempty(S)
return nothing
else
q = dequeue!(S)
q1, q2, q3 = q[1],q[2],q[3]
arcs1 = it.A[q1]
arcs2 = it.B[q2]
w3 = it.filter.rho[q3]
src = Q[q]
for e1 in arcs1, e2 in arcs2
e1, e2, q3_new = phi(it.filter, e1, e2, q3)
if q3_new != 0
n = get_nextstate(e1), get_nextstate(e2), q3_new
if !(n in keys(Q))
i += 1
enqueue!(S,n)
push!(Q, n => i)
end
dest = Q[n]
it.updateC!(it,i,q1,q2,q3,w3,e1,e2,src,dest)
end
end
it.updateCfinal!(it,i,q1,q2,q3,w3,src)
return i, (Q, S, i)
end
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 4681 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
# Depth-first search
export DFS
"""
`DFS(fst::WFST, initial; filter=arc->true)`
Creates an iterator that performs a depth-first search (DFS) of the `fst` starting from the state `initial`.
The function filter can be specify in order to perform the search ignoring arcs with user-defined properties.
For each iterator the tuple `(p,s,n,d,e)` is returned, where:
* `p` is the parent parent state (p==0 if there is no parent)
* `s` is the current state
* `n` next state: `n==0` if `s` has no arcs or if completely explored. These will give you standard DFS iterations.
* `d` is a `Bool`: if `true` means a new state is discovered, can be used to pick up DFS its (see example below)
* `e` is a `Bool`, if `true` means all arcs have been inspected
* `a` inspected arc (empty if `d == false`)
The following cases/colors are possible:
* `d == false && n ==0` -> black state, state has been checked completely
* `d == false && n !=0` -> `n` is already gray
* `d == true -> n` state is colored gray, i.e. is visited for the first time
# Example
```julia
julia> fst = WFST(Dict(1=>1));
julia> add_arc!(fst, 1, 2, 1, 1, 1.0);
julia> add_arc!(fst, 1, 5, 1, 1, 1.0);
julia> add_arc!(fst, 1, 3, 1, 1, 1.0);
julia> add_arc!(fst, 2, 6, 1, 1, 1.0);
julia> add_arc!(fst, 2, 4, 1, 1, 1.0);
julia> add_arc!(fst, 5, 4, 1, 1, 1.0);
julia> add_arc!(fst, 3, 4, 1, 1, 1.0);
julia> add_arc!(fst, 3, 7, 1, 1, 1.0);
julia> initial!(fst,1)
WFST #states: 7, #arcs: 8, #isym: 1, #osym: 1
|1/0.0f0|
1:1/1.0f0 → (2)
1:1/1.0f0 → (5)
1:1/1.0f0 → (3)
(2)
1:1/1.0f0 → (6)
1:1/1.0f0 → (4)
(3)
1:1/1.0f0 → (4)
1:1/1.0f0 → (7)
(4)
(5)
1:1/1.0f0 → (4)
(6)
(7)
julia> dfs = FiniteStateTransducers.DFS(fst,1); # DFS starting from state 1
julia> for (p,s,n,d,e,a) in dfs
println("\$p,\$s,\$n")
if d == true
println("visiting first time \$n (Gray)")
else
if e
println("completed state \$s (Black)")
else
println("node \$n already visited")
end
end
end
0,1,2
visiting first time 2 (Gray)
1,2,6
visiting first time 6 (Gray)
2,6,0
completed state 6 (Black)
1,2,4
visiting first time 4 (Gray)
2,4,0
completed state 4 (Black)
1,2,0
completed state 2 (Black)
0,1,5
visiting first time 5 (Gray)
1,5,4
node 4 already visited
1,5,0
completed state 5 (Black)
0,1,3
visiting first time 3 (Gray)
1,3,4
node 4 already visited
1,3,7
visiting first time 7 (Gray)
3,7,0
completed state 7 (Black)
1,3,0
completed state 3 (Black)
0,1,0
completed state 1 (Black)
```
"""
struct DFS{W, A, D, F <: WFST{W,A,D}}
fst::F
is_visited::Vector{Bool}
is_completed::Vector{Bool} #TODO possibly this can be rm
initial::D
filter::Function
empty_arc::Arc{W,D}
function DFS(fst::F, initial::D; filter=arc->true) where {W,A,D,F <: WFST{W,A,D}}
is_visited = zeros(Bool, length(fst))
is_completed = zeros(Bool, length(fst))
empty_arc = Arc{W,D}(D(0),D(0),W(0),D(0))
new{W,A,D,F}(fst, is_visited, is_completed, initial, filter, empty_arc)
end
end
function init(d::DFS{W,A,D,F}) where {W,A,D,F}
s = d.initial
q = Stack{Tuple{D,D}}()
d.is_visited[s] = true
push!(q,(s,1)) # tuple having (parent state,arc iterator state)
end
function Base.iterate(d::DFS{W,A,D}, q = init(d)) where {W,A,D}
if isempty(q)
return nothing
else
s, arc_it_state = pop!(q)
arcs = d.fst[s]
state_arc = iterate(arcs,arc_it_state)
while state_arc != nothing && (!d.filter(state_arc[1]))
state_arc = iterate(arcs,state_arc[2])
end
if !isempty(q)
p, = first(q)
else
p = D(0)
end
if state_arc == nothing
d.is_completed[s] = true
# s is completed (black)
return (p,s,D(0),false,true,d.empty_arc), q
else
arc, a = state_arc
push!(q,(s,a))
n = get_nextstate(arc)
if !(d.is_visited[n])
d.is_visited[n] = true
push!(q,(n,1))
# n is newly visit and represent DFS indices
# labeled as gray
return (p,s,n,true ,false,arc), q
else
return (p,s,n,false,false,arc), q
end
end
end
end
# simple implementation (just for testing pourposes)
function recursive_dfs(fst, i = get_initial(fst;single=true))
is_visited = zeros(Bool, length(fst))
recursive_dfs!(is_visited, fst, i)
return is_visited
end
function recursive_dfs!(is_visited, fst, i)
# is_visited must be zeros(Bool,length(fst))
is_visited[i] = true
for arc in fst[i]
w = get_nextstate(arc)
if !is_visited[w]
recursive_dfs!(is_visited, fst, w)
end
end
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 994 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export BoolWeight
"""
`BoolWeight(x::Bool)`
| Set | ``\\oplus`` | ``\\otimes`` | ``\\bar{0}`` | ``\\bar{1}`` |
|:-------------:|:--------------------:|:--------------:|:------------:|:------------:|
| ``\\{0,1\\}`` | ``\\lor`` | ``\\land`` | ``0`` | ``1`` |
"""
struct BoolWeight <: Semiring
x::Bool
end
zero(::Type{BoolWeight}) = BoolWeight(false)
one(::Type{BoolWeight}) = BoolWeight(true)
*(a::BoolWeight, b::BoolWeight) = BoolWeight(a.x && b.x)
+(a::BoolWeight, b::BoolWeight) = BoolWeight(a.x || b.x)
#properties
isidempotent(::Type{W}) where {W <: BoolWeight} = true
iscommulative(::Type{W}) where {W <: BoolWeight} = true
isleft(::Type{W}) where {W <: BoolWeight}= true
isright(::Type{W}) where {W <: BoolWeight}= true
ispath(::Type{W}) where {W <: BoolWeight}= true
iscomplete(::Type{W}) where {W <: BoolWeight}= true
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 875 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
# this makes work e.g. TropicalWeight{Float32}(x::TropicalWeight{Float64})
for W in [:TropicalWeight=>:AbstractFloat,
:ProbabilityWeight=>:AbstractFloat,
:NLogWeight=>:AbstractFloat,
:LogWeight=>:AbstractFloat,
]
@eval $(W[1]){T}(x::$(W[1]){TT}) where {T<:$(W[2]),TT<:$(W[2])} = $(W[1]){T}(T(x.x))
@eval $(W[1]){T}(x::$(W[1]){T}) where {T<:$(W[2])} = x
end
for W in [:LeftStringWeight,:RightStringWeight,:BoolWeight,:ProductWeight]
@eval $(W)(x::$(W)) = x
end
#parse
for W in [:TropicalWeight,
:ProbabilityWeight,
:NLogWeight,
:LogWeight,
]
@eval parse(::Type{$(W){T}},str) where T = $(W)(parse(T,str))
end
parse(::Type{S},str) where {S <: BoolWeight} = S(parse(Bool,str))
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1973 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export LeftStringWeight
"""
`LeftStringWeight(x)`
| Set | ``\\oplus`` | ``\\otimes`` | ``\\bar{0}`` | ``\\bar{1}`` |
|:-----------------------:|:----------------------:|:--------------:|:------------:|:------------:|
|``L^*\\cup\\{\\infty\\}``| longest common prefix | ``\\cdot`` |``\\infty`` |``\\epsilon`` |
where ``L^*`` is Kleene closure of the set of characters ``L`` and ``\\epsilon`` the empty string.
"""
struct LeftStringWeight <: Semiring
x::String
iszero::Bool
end
LeftStringWeight(x::String) = LeftStringWeight(x,false)
reversetype(::Type{S}) where {S <: LeftStringWeight} = RightStringWeight
zero(::Type{LeftStringWeight}) = LeftStringWeight("",true)
one(::Type{LeftStringWeight}) = LeftStringWeight("",false)
# longest common prefix
function lcp(a::LeftStringWeight,b::LeftStringWeight)
if a.iszero
return b
elseif b.iszero
return a
else
cnt = 0
for x in zip(a.x,b.x)
if x[1] == x[2]
cnt +=1
else
break
end
end
return LeftStringWeight(a.x[1:cnt])
end
end
*(a::T, b::T) where {T<:LeftStringWeight}=
((a.iszero) | (b.iszero)) ? zero(T) : T(a.x * b.x)
+(a::LeftStringWeight, b::LeftStringWeight) = lcp(a,b)
function /(a::LeftStringWeight, b::LeftStringWeight)
if b == zero(LeftStringWeight)
throw(ErrorException("Cannot divide by zero"))
elseif a == zero(LeftStringWeight)
return zero(LeftStringWeight)
else
str = ""
for i=1:length(a.x)
if i > length(b.x)
str *= a.x[i]
end
end
return LeftStringWeight(str)
end
end
reverse(a::LeftStringWeight) = RightStringWeight(reverse(a.x),a.iszero)
#properties
isidempotent(::Type{W}) where {W <: LeftStringWeight} = true
isleft(::Type{W}) where {W <: LeftStringWeight}= true
isweaklydivisible(::Type{W}) where {W <: LeftStringWeight}= true
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1566 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export LogWeight
"""
`LogWeight(x)`
| Set | ``\\oplus`` | ``\\otimes`` | ``\\bar{0}`` | ``\\bar{1}`` |
|:-----------------------------------:|:--------------------:|:--------------:|:------------:|:------------:|
|``\\mathbb{R}\\cup\\{\\pm\\infty\\}``|``\\log(e^{x}+e^{y})``| ``+`` |``-\\infty`` | ``0`` |
"""
struct LogWeight{T <: AbstractFloat} <: Semiring
x::T
end
LogWeight(x::Number) = LogWeight(float(x))
zero(::Type{LogWeight{T}}) where T = LogWeight{T}(T(-Inf))
one(::Type{LogWeight{T}}) where T = LogWeight{T}(zero(T))
*(a::LogWeight{T}, b::LogWeight{T}) where {T <: AbstractFloat} = LogWeight{T}(a.x + b.x)
+(a::LogWeight{T}, b::LogWeight{T}) where {T <: AbstractFloat} = LogWeight{T}(logadd(a.x,b.x))
/(a::LogWeight{T}, b::LogWeight{T}) where {T <: AbstractFloat} = LogWeight{T}(a.x - b.x)
reverse(a::LogWeight) = a
function logadd(y::T, x::T) where {T <: AbstractFloat}
if isinf(x) return y end
if isinf(y) return x end
if x < y
diff = x-y
x = y
else
diff = y-x
end
return x + log1p(exp(diff))
end
# parsing
parse(::Type{S},str) where {T, S <: LogWeight{T}} = S(parse(T,str))
#properties
iscommulative(::Type{W}) where {W <: LogWeight} = true
isleft(::Type{W}) where {W <: LogWeight} = true
isright(::Type{W}) where {W <: LogWeight}= true
isweaklydivisible(::Type{W}) where {W <: LogWeight}= true
iscomplete(::Type{W}) where {W <: LogWeight}= true
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1393 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export NLogWeight
"""
`NLogWeight(x)`
| Set | ``\\oplus`` | ``\\otimes`` | ``\\bar{0}`` | ``\\bar{1}`` |
|:-----------------------------------:|:-----------------------:|:--------------:|:------------:|:------------:|
|``\\mathbb{R}\\cup\\{\\pm\\infty\\}``|``-\\log(e^{-x}+e^{-y})``| ``+`` |``\\infty`` | ``0`` |
"""
struct NLogWeight{T <: AbstractFloat} <: Semiring
x::T
end
NLogWeight(x::Number) = NLogWeight(float(x))
zero(::Type{NLogWeight{T}}) where T = NLogWeight{T}(T(Inf))
one(::Type{NLogWeight{T}}) where T = NLogWeight{T}(zero(T))
*(a::NLogWeight{T}, b::NLogWeight{T}) where {T <: AbstractFloat} = NLogWeight{T}(a.x + b.x)
+(a::NLogWeight{T}, b::NLogWeight{T}) where {T <: AbstractFloat} = NLogWeight{T}(-logadd(-a.x,-b.x))
/(a::NLogWeight{T}, b::NLogWeight{T}) where {T <: AbstractFloat} = NLogWeight{T}(a.x - b.x)
reverse(a::NLogWeight) = a
# parsing
parse(::Type{S},str) where {T, S <: NLogWeight{T}} = S(parse(T,str))
#properties
iscommulative(::Type{W}) where {W <: NLogWeight} = true
isleft(::Type{W}) where {W <: NLogWeight} = true
isright(::Type{W}) where {W <: NLogWeight}= true
isweaklydivisible(::Type{W}) where {W <: NLogWeight}= true
iscomplete(::Type{W}) where {W <: NLogWeight}= true
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 1278 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export ProbabilityWeight
"""
`ProbabilityWeight(x)`
| Set |``\\oplus`` | ``\\otimes`` | ``\\bar{0}`` | ``\\bar{1}`` |
|:--------------:|:------------:|:--------------:|:------------:|:------------:|
|``\\mathbb{R}`` | + | * | ``0`` | ``1`` |
"""
struct ProbabilityWeight{T <: AbstractFloat} <: Semiring
x::T
end
zero(::Type{ProbabilityWeight{T}}) where T = ProbabilityWeight{T}(zero(T))
one(::Type{ProbabilityWeight{T}}) where T = ProbabilityWeight{T}(one(T))
*(a::ProbabilityWeight{T}, b::ProbabilityWeight{T}) where {T <: AbstractFloat} = ProbabilityWeight{T}(a.x * b.x)
+(a::ProbabilityWeight{T}, b::ProbabilityWeight{T}) where {T <: AbstractFloat} = ProbabilityWeight{T}(a.x + b.x)
/(a::ProbabilityWeight{T}, b::ProbabilityWeight{T}) where {T <: AbstractFloat} = ProbabilityWeight{T}(a.x / b.x)
# properties
iscommulative(::Type{W}) where {W<:ProbabilityWeight} = true
isleft(::Type{W}) where {W<:ProbabilityWeight} = true
isright(::Type{W}) where {W<:ProbabilityWeight} = true
isweaklydivisible(::Type{W}) where {W <: ProbabilityWeight}= true
iscomplete(::Type{W}) where {W <: ProbabilityWeight} = true
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
|
[
"MIT"
] | 0.1.0 | 42d75e0b4f7cbdc29911175ddaa61f14293c6f19 | code | 2489 | # Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Niccolò Antonello <[email protected]>
export ProductWeight
"""
`ProductWeight(x...)`
| Set | ``\\oplus`` | ``\\otimes`` | ``\\bar{0}`` | ``\\bar{1}`` |
|:-------------------------------------------------:|:-------------------------------------------------------------------------:|:---------------------------------------------------------------------------:|:------------------------------------------------------------:|:------------------------------------------------------------:|
|``\\mathbb{W}_1\\times \\dots\\times\\mathbb{W}_N``| ``\\oplus_{\\mathbb{W}_1} \\times \\dots\\times\\oplus_{\\mathbb{W}_N}`` | ``\\otimes_{\\mathbb{W}_1} \\times \\dots\\times\\otimes_{\\mathbb{W}_N}`` |``(\\bar{0}_{\\mathbb{W}_1},\\dots,\\bar{0}_{\\mathbb{W}_N})``|``(\\bar{1}_{\\mathbb{W}_1},\\dots,\\bar{1}_{\\mathbb{W}_N})``|
"""
struct ProductWeight{N, T <:NTuple{N,Semiring} } <: Semiring
x::T
end
ProductWeight(x...) = ProductWeight(x)
reversetype(::Type{S}) where {N,T,S <: ProductWeight{N,T}} =
# in future we can use fieldtypes instead of ntuple(i -> fieldtype(T, i), fieldcount(T))
ProductWeight{N,Tuple{reversetype.(ntuple(i -> fieldtype(T, i), fieldcount(T)))...}}
ProductWeight{N,T}(x::ProductWeight{N,T}) where {N,T <:NTuple{N,Semiring}} = x
zero(::Type{ProductWeight{N,T}}) where {N,T} = ProductWeight{N,T}(zero.(ntuple(i -> fieldtype(T, i), fieldcount(T))))
one(::Type{ProductWeight{N,T}}) where {N,T} = ProductWeight{N,T}(one.(ntuple(i -> fieldtype(T, i), fieldcount(T))))
*(a::ProductWeight{N,T}, b::ProductWeight{N,T}) where {N,T} = ProductWeight{N,T}(a.x .* b.x)
+(a::ProductWeight{N,T}, b::ProductWeight{N,T}) where {N,T} = ProductWeight{N,T}(a.x .+ b.x)
/(a::ProductWeight{N,T}, b::ProductWeight{N,T}) where {N,T} = ProductWeight{N,T}(a.x ./ b.x)
reverse(a::ProductWeight{N,T}) where {N,T} = ProductWeight{N,T}t(reverse.(a.x))
# properties
for p in [:isleft,
:isright,
:isweaklydivisible,
:ispath,
:isidempotent,
:iscommulative,
:iscomplete]
@eval $p(::Type{ProductWeight{N,T}}) where {N,T} = all( $p.(ntuple(i -> fieldtype(T, i), fieldcount(T))) )
end
| FiniteStateTransducers | https://github.com/idiap/FiniteStateTransducers.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.