import * as Chunk from "@effect/data/Chunk"
import { dual, pipe } from "@effect/data/Function"
import * as MutableQueue from "@effect/data/MutableQueue"
import * as MutableRef from "@effect/data/MutableRef"
import * as Option from "@effect/data/Option"
import { pipeArguments } from "@effect/data/Pipeable"
import type * as Deferred from "@effect/io/Deferred"
import type * as Effect from "@effect/io/Effect"
import type * as Hub from "@effect/io/Hub"
import * as cause from "@effect/io/internal/cause"
import * as core from "@effect/io/internal/core"
import * as executionStrategy from "@effect/io/internal/executionStrategy"
import * as fiberRuntime from "@effect/io/internal/fiberRuntime"
import * as queue from "@effect/io/internal/queue"
import type * as Queue from "@effect/io/Queue"
import type * as Scope from "@effect/io/Scope"
/** @internal */
export interface AtomicHub {
readonly capacity: number
isEmpty(): boolean
isFull(): boolean
size(): number
publish(value: A): boolean
publishAll(elements: Iterable): Chunk.Chunk
slide(): void
subscribe(): Subscription
}
/** @internal */
interface Subscription {
isEmpty(): boolean
size(): number
poll(default_: D): A | D
pollUpTo(n: number): Chunk.Chunk
unsubscribe(): void
}
/** @internal */
type Subscribers = Map<
Subscription,
Set>>
>
const addSubscribers = (
subscription: Subscription,
pollers: MutableQueue.MutableQueue>
) =>
(subscribers: Subscribers) => {
if (!subscribers.has(subscription)) {
subscribers.set(subscription, new Set())
}
const set = subscribers.get(subscription)!
set.add(pollers)
}
const removeSubscribers = (
subscription: Subscription,
pollers: MutableQueue.MutableQueue>
) =>
(subscribers: Subscribers) => {
if (!subscribers.has(subscription)) {
return
}
const set = subscribers.get(subscription)!
set.delete(pollers)
if (set.size === 0) {
subscribers.delete(subscription)
}
}
/** @internal */
export const bounded = (requestedCapacity: number): Effect.Effect> =>
pipe(
core.sync(() => makeBoundedHub(requestedCapacity)),
core.flatMap((atomicHub) => makeHub(atomicHub, new BackPressureStrategy()))
)
/** @internal */
export const dropping = (requestedCapacity: number): Effect.Effect> =>
pipe(
core.sync(() => makeBoundedHub(requestedCapacity)),
core.flatMap((atomicHub) => makeHub(atomicHub, new DroppingStrategy()))
)
/** @internal */
export const sliding = (requestedCapacity: number): Effect.Effect> =>
pipe(
core.sync(() => makeBoundedHub(requestedCapacity)),
core.flatMap((atomicHub) => makeHub(atomicHub, new SlidingStrategy()))
)
/** @internal */
export const unbounded = (): Effect.Effect> =>
pipe(
core.sync(() => makeUnboundedHub()),
core.flatMap((atomicHub) => makeHub(atomicHub, new DroppingStrategy()))
)
/** @internal */
export const capacity = (self: Hub.Hub): number => self.capacity()
/** @internal */
export const size = (self: Hub.Hub): Effect.Effect => self.size()
/** @internal */
export const isFull = (self: Hub.Hub): Effect.Effect => self.isFull()
/** @internal */
export const isEmpty = (self: Hub.Hub): Effect.Effect => self.isEmpty()
/** @internal */
export const shutdown = (self: Hub.Hub): Effect.Effect => self.shutdown()
/** @internal */
export const isShutdown = (self: Hub.Hub): Effect.Effect => self.isShutdown()
/** @internal */
export const awaitShutdown = (self: Hub.Hub): Effect.Effect => self.awaitShutdown()
/** @internal */
export const publish = dual<
(value: A) => (self: Hub.Hub) => Effect.Effect,
(self: Hub.Hub, value: A) => Effect.Effect
>(2, (self, value) => self.publish(value))
/** @internal */
export const publishAll = dual<
(elements: Iterable) => (self: Hub.Hub) => Effect.Effect,
(self: Hub.Hub, elements: Iterable) => Effect.Effect
>(2, (self, elements) => self.publishAll(elements))
/** @internal */
export const subscribe = (self: Hub.Hub): Effect.Effect> => self.subscribe()
/** @internal */
const makeBoundedHub = (requestedCapacity: number): AtomicHub => {
ensureCapacity(requestedCapacity)
if (requestedCapacity === 1) {
return new BoundedHubSingle()
} else if (nextPow2(requestedCapacity) === requestedCapacity) {
return new BoundedHubPow2(requestedCapacity)
} else {
return new BoundedHubArb(requestedCapacity)
}
}
/** @internal */
const makeUnboundedHub = (): AtomicHub => {
return new UnboundedHub()
}
/** @internal */
const makeSubscription = (
hub: AtomicHub,
subscribers: Subscribers,
strategy: HubStrategy
): Effect.Effect> =>
core.map(core.deferredMake(), (deferred) =>
unsafeMakeSubscription(
hub,
subscribers,
hub.subscribe(),
MutableQueue.unbounded>(),
deferred,
MutableRef.make(false),
strategy
))
/** @internal */
export const unsafeMakeSubscription = (
hub: AtomicHub,
subscribers: Subscribers,
subscription: Subscription,
pollers: MutableQueue.MutableQueue>,
shutdownHook: Deferred.Deferred,
shutdownFlag: MutableRef.MutableRef,
strategy: HubStrategy
): Queue.Dequeue => {
return new SubscriptionImpl(
hub,
subscribers,
subscription,
pollers,
shutdownHook,
shutdownFlag,
strategy
)
}
/** @internal */
class BoundedHubArb implements AtomicHub {
array: Array
publisherIndex = 0
subscribers: Array
subscriberCount = 0
subscribersIndex = 0
readonly capacity: number
constructor(requestedCapacity: number) {
this.array = Array.from({ length: requestedCapacity })
this.subscribers = Array.from({ length: requestedCapacity })
this.capacity = requestedCapacity
}
isEmpty(): boolean {
return this.publisherIndex === this.subscribersIndex
}
isFull(): boolean {
return this.publisherIndex === this.subscribersIndex + this.capacity
}
size(): number {
return this.publisherIndex - this.subscribersIndex
}
publish(value: A): boolean {
if (this.isFull()) {
return false
}
if (this.subscriberCount !== 0) {
const index = this.publisherIndex % this.capacity
this.array[index] = value
this.subscribers[index] = this.subscriberCount
this.publisherIndex += 1
}
return true
}
publishAll(elements: Iterable): Chunk.Chunk {
const chunk = Chunk.fromIterable(elements)
const n = chunk.length
const size = this.publisherIndex - this.subscribersIndex
const available = this.capacity - size
const forHub = Math.min(n, available)
if (forHub === 0) {
return chunk
}
let iteratorIndex = 0
const publishAllIndex = this.publisherIndex + forHub
while (this.publisherIndex !== publishAllIndex) {
const a = Chunk.unsafeGet(chunk, iteratorIndex++)
const index = this.publisherIndex % this.capacity
this.array[index] = a
this.subscribers[index] = this.subscriberCount
this.publisherIndex += 1
}
return Chunk.drop(chunk, iteratorIndex)
}
slide(): void {
if (this.subscribersIndex !== this.publisherIndex) {
const index = this.subscribersIndex % this.capacity
this.array[index] = null as unknown as A
this.subscribers[index] = 0
this.subscribersIndex += 1
}
}
subscribe(): Subscription {
this.subscriberCount += 1
return new BoundedHubArbSubscription(this, this.publisherIndex, false)
}
}
class BoundedHubArbSubscription implements Subscription {
constructor(
private self: BoundedHubArb,
private subscriberIndex: number,
private unsubscribed: boolean
) {
}
isEmpty(): boolean {
return (
this.unsubscribed ||
this.self.publisherIndex === this.subscriberIndex ||
this.self.publisherIndex === this.self.subscribersIndex
)
}
size() {
if (this.unsubscribed) {
return 0
}
return this.self.publisherIndex - Math.max(this.subscriberIndex, this.self.subscribersIndex)
}
poll(default_: D): A | D {
if (this.unsubscribed) {
return default_
}
this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex)
if (this.subscriberIndex !== this.self.publisherIndex) {
const index = this.subscriberIndex % this.self.capacity
const elem = this.self.array[index]!
this.self.subscribers[index] -= 1
if (this.self.subscribers[index] === 0) {
this.self.array[index] = null as unknown as A
this.self.subscribersIndex += 1
}
this.subscriberIndex += 1
return elem
}
return default_
}
pollUpTo(n: number): Chunk.Chunk {
if (this.unsubscribed) {
return Chunk.empty()
}
this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex)
const size = this.self.publisherIndex - this.subscriberIndex
const toPoll = Math.min(n, size)
if (toPoll <= 0) {
return Chunk.empty()
}
const builder: Array = []
const pollUpToIndex = this.subscriberIndex + toPoll
while (this.subscriberIndex !== pollUpToIndex) {
const index = this.subscriberIndex % this.self.capacity
const a = this.self.array[index] as A
this.self.subscribers[index] -= 1
if (this.self.subscribers[index] === 0) {
this.self.array[index] = null as unknown as A
this.self.subscribersIndex += 1
}
builder.push(a)
this.subscriberIndex += 1
}
return Chunk.fromIterable(builder)
}
unsubscribe(): void {
if (!this.unsubscribed) {
this.unsubscribed = true
this.self.subscriberCount -= 1
this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex)
while (this.subscriberIndex !== this.self.publisherIndex) {
const index = this.subscriberIndex % this.self.capacity
this.self.subscribers[index] -= 1
if (this.self.subscribers[index] === 0) {
this.self.array[index] = null as unknown as A
this.self.subscribersIndex += 1
}
this.subscriberIndex += 1
}
}
}
}
/** @internal */
class BoundedHubPow2 implements AtomicHub {
array: Array
mask: number
publisherIndex = 0
subscribers: Array
subscriberCount = 0
subscribersIndex = 0
readonly capacity: number
constructor(requestedCapacity: number) {
this.array = Array.from({ length: requestedCapacity })
this.mask = requestedCapacity - 1
this.subscribers = Array.from({ length: requestedCapacity })
this.capacity = requestedCapacity
}
isEmpty(): boolean {
return this.publisherIndex === this.subscribersIndex
}
isFull(): boolean {
return this.publisherIndex === this.subscribersIndex + this.capacity
}
size(): number {
return this.publisherIndex - this.subscribersIndex
}
publish(value: A): boolean {
if (this.isFull()) {
return false
}
if (this.subscriberCount !== 0) {
const index = this.publisherIndex & this.mask
this.array[index] = value
this.subscribers[index] = this.subscriberCount
this.publisherIndex += 1
}
return true
}
publishAll(elements: Iterable): Chunk.Chunk {
const chunk = Chunk.fromIterable(elements)
const n = chunk.length
const size = this.publisherIndex - this.subscribersIndex
const available = this.capacity - size
const forHub = Math.min(n, available)
if (forHub === 0) {
return chunk
}
let iteratorIndex = 0
const publishAllIndex = this.publisherIndex + forHub
while (this.publisherIndex !== publishAllIndex) {
const elem = Chunk.unsafeGet(chunk, iteratorIndex++)
const index = this.publisherIndex & this.mask
this.array[index] = elem
this.subscribers[index] = this.subscriberCount
this.publisherIndex += 1
}
return Chunk.drop(chunk, iteratorIndex)
}
slide(): void {
if (this.subscribersIndex !== this.publisherIndex) {
const index = this.subscribersIndex & this.mask
this.array[index] = null as unknown as A
this.subscribers[index] = 0
this.subscribersIndex += 1
}
}
subscribe(): Subscription {
this.subscriberCount += 1
return new BoundedHubPow2Subscription(this, this.publisherIndex, false)
}
}
/** @internal */
class BoundedHubPow2Subscription implements Subscription {
constructor(
private self: BoundedHubPow2,
private subscriberIndex: number,
private unsubscribed: boolean
) {
}
isEmpty(): boolean {
return (
this.unsubscribed ||
this.self.publisherIndex === this.subscriberIndex ||
this.self.publisherIndex === this.self.subscribersIndex
)
}
size() {
if (this.unsubscribed) {
return 0
}
return this.self.publisherIndex - Math.max(this.subscriberIndex, this.self.subscribersIndex)
}
poll(default_: D): A | D {
if (this.unsubscribed) {
return default_
}
this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex)
if (this.subscriberIndex !== this.self.publisherIndex) {
const index = this.subscriberIndex & this.self.mask
const elem = this.self.array[index]!
this.self.subscribers[index] -= 1
if (this.self.subscribers[index] === 0) {
this.self.array[index] = null as unknown as A
this.self.subscribersIndex += 1
}
this.subscriberIndex += 1
return elem
}
return default_
}
pollUpTo(n: number): Chunk.Chunk {
if (this.unsubscribed) {
return Chunk.empty()
}
this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex)
const size = this.self.publisherIndex - this.subscriberIndex
const toPoll = Math.min(n, size)
if (toPoll <= 0) {
return Chunk.empty()
}
const builder: Array = []
const pollUpToIndex = this.subscriberIndex + toPoll
while (this.subscriberIndex !== pollUpToIndex) {
const index = this.subscriberIndex & this.self.mask
const elem = this.self.array[index] as A
this.self.subscribers[index] -= 1
if (this.self.subscribers[index] === 0) {
this.self.array[index] = null as unknown as A
this.self.subscribersIndex += 1
}
builder.push(elem)
this.subscriberIndex += 1
}
return Chunk.fromIterable(builder)
}
unsubscribe(): void {
if (!this.unsubscribed) {
this.unsubscribed = true
this.self.subscriberCount -= 1
this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex)
while (this.subscriberIndex !== this.self.publisherIndex) {
const index = this.subscriberIndex & this.self.mask
this.self.subscribers[index] -= 1
if (this.self.subscribers[index] === 0) {
this.self.array[index] = null as unknown as A
this.self.subscribersIndex += 1
}
this.subscriberIndex += 1
}
}
}
}
/** @internal */
class BoundedHubSingle implements AtomicHub {
publisherIndex = 0
subscriberCount = 0
subscribers = 0
value: A = null as unknown as A
readonly capacity = 1
pipe() {
return pipeArguments(this, arguments)
}
isEmpty(): boolean {
return this.subscribers === 0
}
isFull(): boolean {
return !this.isEmpty()
}
size(): number {
return this.isEmpty() ? 0 : 1
}
publish(value: A): boolean {
if (this.isFull()) {
return false
}
if (this.subscriberCount !== 0) {
this.value = value
this.subscribers = this.subscriberCount
this.publisherIndex += 1
}
return true
}
publishAll(elements: Iterable): Chunk.Chunk {
const chunk = Chunk.fromIterable(elements)
if (Chunk.isEmpty(chunk)) {
return chunk
}
if (this.publish(Chunk.unsafeHead(chunk))) {
return Chunk.drop(chunk, 1)
} else {
return chunk
}
}
slide(): void {
if (this.isFull()) {
this.subscribers = 0
this.value = null as unknown as A
}
}
subscribe(): Subscription {
this.subscriberCount += 1
return new BoundedHubSingleSubscription(this, this.publisherIndex, false)
}
}
/** @internal */
class BoundedHubSingleSubscription implements Subscription {
constructor(
private self: BoundedHubSingle,
private subscriberIndex: number,
private unsubscribed: boolean
) {
}
isEmpty(): boolean {
return (
this.unsubscribed ||
this.self.subscribers === 0 ||
this.subscriberIndex === this.self.publisherIndex
)
}
size() {
return this.isEmpty() ? 0 : 1
}
poll(default_: D): A | D {
if (this.isEmpty()) {
return default_
}
const elem = this.self.value
this.self.subscribers -= 1
if (this.self.subscribers === 0) {
this.self.value = null as unknown as A
}
this.subscriberIndex += 1
return elem
}
pollUpTo(n: number): Chunk.Chunk {
if (this.isEmpty() || n < 1) {
return Chunk.empty()
}
const a = this.self.value
this.self.subscribers -= 1
if (this.self.subscribers === 0) {
this.self.value = null as unknown as A
}
this.subscriberIndex += 1
return Chunk.of(a)
}
unsubscribe(): void {
if (!this.unsubscribed) {
this.unsubscribed = true
this.self.subscriberCount -= 1
if (this.subscriberIndex !== this.self.publisherIndex) {
this.self.subscribers -= 1
if (this.self.subscribers === 0) {
this.self.value = null as unknown as A
}
}
}
}
}
/** @internal */
class Node {
constructor(
public value: A | null,
public subscribers: number,
public next: Node | null
) {
}
}
/** @internal */
class UnboundedHub implements AtomicHub {
publisherHead = new Node(null, 0, null)
publisherIndex = 0
publisherTail: Node
subscribersIndex = 0
readonly capacity = Number.MAX_SAFE_INTEGER
constructor() {
this.publisherTail = this.publisherHead
}
isEmpty(): boolean {
return this.publisherHead === this.publisherTail
}
isFull(): boolean {
return false
}
size(): number {
return this.publisherIndex - this.subscribersIndex
}
publish(value: A): boolean {
const subscribers = this.publisherTail.subscribers
if (subscribers !== 0) {
this.publisherTail.next = new Node(value, subscribers, null)
this.publisherTail = this.publisherTail.next
this.publisherIndex += 1
}
return true
}
publishAll(elements: Iterable): Chunk.Chunk {
for (const a of elements) {
this.publish(a)
}
return Chunk.empty()
}
slide(): void {
if (this.publisherHead !== this.publisherTail) {
this.publisherHead = this.publisherHead.next!
this.publisherHead.value = null
this.subscribersIndex += 1
}
}
subscribe(): Subscription {
this.publisherTail.subscribers += 1
return new UnboundedHubSubscription(
this,
this.publisherTail,
this.publisherIndex,
false
)
}
}
/** @internal */
class UnboundedHubSubscription implements Subscription {
constructor(
private self: UnboundedHub,
private subscriberHead: Node,
private subscriberIndex: number,
private unsubscribed: boolean
) {
}
isEmpty(): boolean {
if (this.unsubscribed) {
return true
}
let empty = true
let loop = true
while (loop) {
if (this.subscriberHead === this.self.publisherTail) {
loop = false
} else {
if (this.subscriberHead.next!.value !== null) {
empty = false
loop = false
} else {
this.subscriberHead = this.subscriberHead.next!
this.subscriberIndex += 1
}
}
}
return empty
}
size() {
if (this.unsubscribed) {
return 0
}
return this.self.publisherIndex - Math.max(this.subscriberIndex, this.self.subscribersIndex)
}
poll(default_: D): A | D {
if (this.unsubscribed) {
return default_
}
let loop = true
let polled: A | D = default_
while (loop) {
if (this.subscriberHead === this.self.publisherTail) {
loop = false
} else {
const elem = this.subscriberHead.next!.value
if (elem !== null) {
polled = elem
this.subscriberHead.subscribers -= 1
if (this.subscriberHead.subscribers === 0) {
this.self.publisherHead = this.self.publisherHead.next!
this.self.publisherHead.value = null
this.self.subscribersIndex += 1
}
loop = false
}
this.subscriberHead = this.subscriberHead.next!
this.subscriberIndex += 1
}
}
return polled
}
pollUpTo(n: number): Chunk.Chunk {
const builder: Array = []
const default_ = null
let i = 0
while (i !== n) {
const a = this.poll(default_ as unknown as A)
if (a === default_) {
i = n
} else {
builder.push(a)
i += 1
}
}
return Chunk.fromIterable(builder)
}
unsubscribe(): void {
if (!this.unsubscribed) {
this.unsubscribed = true
this.self.publisherTail.subscribers -= 1
while (this.subscriberHead !== this.self.publisherTail) {
if (this.subscriberHead.next!.value !== null) {
this.subscriberHead.subscribers -= 1
if (this.subscriberHead.subscribers === 0) {
this.self.publisherHead = this.self.publisherHead.next!
this.self.publisherHead.value = null
this.self.subscribersIndex += 1
}
}
this.subscriberHead = this.subscriberHead.next!
}
}
}
}
/** @internal */
class SubscriptionImpl implements Queue.Dequeue {
[queue.DequeueTypeId] = queue.dequeueVariance
constructor(
readonly hub: AtomicHub,
readonly subscribers: Subscribers,
readonly subscription: Subscription,
readonly pollers: MutableQueue.MutableQueue>,
readonly shutdownHook: Deferred.Deferred,
readonly shutdownFlag: MutableRef.MutableRef,
readonly strategy: HubStrategy
) {
}
pipe() {
return pipeArguments(this, arguments)
}
capacity(): number {
return this.hub.capacity
}
isActive(): boolean {
return !MutableRef.get(this.shutdownFlag)
}
size(): Effect.Effect {
return core.suspend(() =>
MutableRef.get(this.shutdownFlag)
? core.interrupt
: core.succeed(this.subscription.size())
)
}
unsafeSize(): Option.Option {
if (MutableRef.get(this.shutdownFlag)) {
return Option.none()
}
return Option.some(this.subscription.size())
}
isFull(): Effect.Effect {
return core.map(this.size(), (size) => size === this.capacity())
}
isEmpty(): Effect.Effect {
return core.map(this.size(), (size) => size === 0)
}
shutdown(): Effect.Effect {
return core.uninterruptible(
core.withFiberRuntime((state) => {
MutableRef.set(this.shutdownFlag, true)
return pipe(
fiberRuntime.forEachParUnbounded(
unsafePollAllQueue(this.pollers),
(d) => core.deferredInterruptWith(d, state.id()),
false
),
core.zipRight(core.sync(() => {
this.subscribers.delete(this.subscription)
this.subscription.unsubscribe()
this.strategy.unsafeOnHubEmptySpace(this.hub, this.subscribers)
})),
core.whenEffect(core.deferredSucceed(this.shutdownHook, void 0)),
core.asUnit
)
})
)
}
isShutdown(): Effect.Effect {
return core.sync(() => MutableRef.get(this.shutdownFlag))
}
awaitShutdown(): Effect.Effect {
return core.deferredAwait(this.shutdownHook)
}
take(): Effect.Effect {
return core.withFiberRuntime((state) => {
if (MutableRef.get(this.shutdownFlag)) {
return core.interrupt
}
const message = MutableQueue.isEmpty(this.pollers)
? this.subscription.poll(MutableQueue.EmptyMutableQueue)
: MutableQueue.EmptyMutableQueue
if (message === MutableQueue.EmptyMutableQueue) {
const deferred = core.deferredUnsafeMake(state.id())
return pipe(
core.suspend(() => {
pipe(this.pollers, MutableQueue.offer(deferred))
pipe(this.subscribers, addSubscribers(this.subscription, this.pollers))
this.strategy.unsafeCompletePollers(
this.hub,
this.subscribers,
this.subscription,
this.pollers
)
return MutableRef.get(this.shutdownFlag) ? core.interrupt : core.deferredAwait(deferred)
}),
core.onInterrupt(() => core.sync(() => unsafeRemove(this.pollers, deferred)))
)
} else {
this.strategy.unsafeOnHubEmptySpace(this.hub, this.subscribers)
return core.succeed(message)
}
})
}
takeAll(): Effect.Effect> {
return core.suspend(() => {
if (MutableRef.get(this.shutdownFlag)) {
return core.interrupt
}
const as = MutableQueue.isEmpty(this.pollers)
? unsafePollAllSubscription(this.subscription)
: Chunk.empty()
this.strategy.unsafeOnHubEmptySpace(this.hub, this.subscribers)
return core.succeed(as)
})
}
takeUpTo(this: this, max: number): Effect.Effect> {
return core.suspend(() => {
if (MutableRef.get(this.shutdownFlag)) {
return core.interrupt
}
const as = MutableQueue.isEmpty(this.pollers)
? unsafePollN(this.subscription, max)
: Chunk.empty()
this.strategy.unsafeOnHubEmptySpace(this.hub, this.subscribers)
return core.succeed(as)
})
}
takeBetween(min: number, max: number): Effect.Effect> {
return core.suspend(() => takeRemainderLoop(this, min, max, Chunk.empty()))
}
}
/** @internal */
const takeRemainderLoop = (
self: Queue.Dequeue,
min: number,
max: number,
acc: Chunk.Chunk
): Effect.Effect> => {
if (max < min) {
return core.succeed(acc)
}
return pipe(
self.takeUpTo(max),
core.flatMap((bs) => {
const remaining = min - bs.length
if (remaining === 1) {
return pipe(self.take(), core.map((b) => pipe(acc, Chunk.appendAll(bs), Chunk.append(b))))
}
if (remaining > 1) {
return pipe(
self.take(),
core.flatMap((b) =>
takeRemainderLoop(
self,
remaining - 1,
max - bs.length - 1,
pipe(acc, Chunk.appendAll(bs), Chunk.append(b))
)
)
)
}
return core.succeed(pipe(acc, Chunk.appendAll(bs)))
})
)
}
/** @internal */
class HubImpl implements Hub.Hub {
readonly [queue.EnqueueTypeId] = queue.enqueueVariance
constructor(
readonly hub: AtomicHub,
readonly subscribers: Subscribers,
readonly scope: Scope.Scope.Closeable,
readonly shutdownHook: Deferred.Deferred,
readonly shutdownFlag: MutableRef.MutableRef,
readonly strategy: HubStrategy
) {
}
capacity(): number {
return this.hub.capacity
}
size(): Effect.Effect {
return core.suspend(() =>
MutableRef.get(this.shutdownFlag) ?
core.interrupt :
core.sync(() => this.hub.size())
)
}
unsafeSize(): Option.Option {
if (MutableRef.get(this.shutdownFlag)) {
return Option.none()
}
return Option.some(this.hub.size())
}
isFull(): Effect.Effect {
return core.map(this.size(), (size) => size === this.capacity())
}
isEmpty(): Effect.Effect {
return core.map(this.size(), (size) => size === 0)
}
awaitShutdown(): Effect.Effect {
return core.deferredAwait(this.shutdownHook)
}
isShutdown(): Effect.Effect {
return core.sync(() => MutableRef.get(this.shutdownFlag))
}
shutdown(): Effect.Effect {
return core.uninterruptible(core.withFiberRuntime((state) => {
pipe(this.shutdownFlag, MutableRef.set(true))
return pipe(
this.scope.close(core.exitInterrupt(state.id())),
core.zipRight(this.strategy.shutdown()),
core.whenEffect(core.deferredSucceed(this.shutdownHook, void 0)),
core.asUnit
)
}))
}
publish(value: A): Effect.Effect {
return core.suspend(() => {
if (MutableRef.get(this.shutdownFlag)) {
return core.interrupt
}
if ((this.hub as AtomicHub).publish(value)) {
this.strategy.unsafeCompleteSubscribers(this.hub, this.subscribers)
return core.succeed(true)
}
return this.strategy.handleSurplus(
this.hub,
this.subscribers,
Chunk.of(value),
this.shutdownFlag
)
})
}
isActive(): boolean {
return !MutableRef.get(this.shutdownFlag)
}
unsafeOffer(value: A): boolean {
if (MutableRef.get(this.shutdownFlag)) {
return false
}
if ((this.hub as AtomicHub).publish(value)) {
this.strategy.unsafeCompleteSubscribers(this.hub, this.subscribers)
return true
}
return false
}
publishAll(elements: Iterable): Effect.Effect {
return core.suspend(() => {
if (MutableRef.get(this.shutdownFlag)) {
return core.interrupt
}
const surplus = unsafePublishAll(this.hub, elements)
this.strategy.unsafeCompleteSubscribers(this.hub, this.subscribers)
if (Chunk.isEmpty(surplus)) {
return core.succeed(true)
}
return this.strategy.handleSurplus(
this.hub,
this.subscribers,
surplus,
this.shutdownFlag
)
})
}
subscribe(): Effect.Effect> {
const acquire = core.tap(
fiberRuntime.all([
this.scope.fork(executionStrategy.sequential),
makeSubscription(this.hub, this.subscribers, this.strategy)
]),
(tuple) => tuple[0].addFinalizer(() => tuple[1].shutdown())
)
return core.map(
fiberRuntime.acquireRelease(acquire, (tuple, exit) => tuple[0].close(exit)),
(tuple) => tuple[1]
)
}
offer(value: A): Effect.Effect {
return this.publish(value)
}
offerAll(elements: Iterable): Effect.Effect {
return this.publishAll(elements)
}
pipe() {
return pipeArguments(this, arguments)
}
}
/** @internal */
export const makeHub = (
hub: AtomicHub,
strategy: HubStrategy
): Effect.Effect> =>
core.flatMap(
fiberRuntime.scopeMake(),
(scope) =>
core.map(core.deferredMake(), (deferred) =>
unsafeMakeHub(
hub,
new Map(),
scope,
deferred,
MutableRef.make(false),
strategy
))
)
/** @internal */
export const unsafeMakeHub = (
hub: AtomicHub,
subscribers: Subscribers,
scope: Scope.Scope.Closeable,
shutdownHook: Deferred.Deferred,
shutdownFlag: MutableRef.MutableRef,
strategy: HubStrategy
): Hub.Hub => {
return new HubImpl(hub, subscribers, scope, shutdownHook, shutdownFlag, strategy)
}
/** @internal */
const nextPow2 = (n: number): number => {
const nextPow = Math.ceil(Math.log(n) / Math.log(2.0))
return Math.max(Math.pow(2, nextPow), 2)
}
/** @internal */
const ensureCapacity = (capacity: number): void => {
if (capacity <= 0) {
throw cause.InvalidHubCapacityException(`Cannot construct Hub with capacity of ${capacity}`)
}
}
/** @internal */
const unsafeCompleteDeferred = (deferred: Deferred.Deferred, a: A): void => {
core.deferredUnsafeDone(deferred, core.succeed(a))
}
/** @internal */
const unsafeOfferAll = (queue: MutableQueue.MutableQueue, as: Iterable): Chunk.Chunk => {
return pipe(queue, MutableQueue.offerAll(as))
}
/** @internal */
const unsafePollAllQueue = (queue: MutableQueue.MutableQueue): Chunk.Chunk => {
return pipe(queue, MutableQueue.pollUpTo(Number.POSITIVE_INFINITY))
}
/** @internal */
const unsafePollAllSubscription = (subscription: Subscription): Chunk.Chunk => {
return subscription.pollUpTo(Number.POSITIVE_INFINITY)
}
/** @internal */
const unsafePollN = (subscription: Subscription, max: number): Chunk.Chunk => {
return subscription.pollUpTo(max)
}
/** @internal */
const unsafePublishAll = (hub: AtomicHub, as: Iterable): Chunk.Chunk => {
return hub.publishAll(as)
}
/** @internal */
const unsafeRemove = (queue: MutableQueue.MutableQueue, value: A): void => {
unsafeOfferAll(
queue,
pipe(unsafePollAllQueue(queue), Chunk.filter((elem) => elem !== value))
)
}
// -----------------------------------------------------------------------------
// Hub.Strategy
// -----------------------------------------------------------------------------
/**
* A `HubStrategy` describes the protocol for how publishers and subscribers
* will communicate with each other through the hub.
*
* @internal
*/
export interface HubStrategy {
/**
* Describes any finalization logic associated with this strategy.
*/
shutdown(): Effect.Effect
/**
* Describes how publishers should signal to subscribers that they are
* waiting for space to become available in the hub.
*/
handleSurplus(
hub: AtomicHub,
subscribers: Subscribers,
elements: Iterable,
isShutdown: MutableRef.MutableRef
): Effect.Effect
/**
* Describes how subscribers should signal to publishers waiting for space
* to become available in the hub that space may be available.
*/
unsafeOnHubEmptySpace(
hub: AtomicHub,
subscribers: Subscribers
): void
/**
* Describes how subscribers waiting for additional values from the hub
* should take those values and signal to publishers that they are no
* longer waiting for additional values.
*/
unsafeCompletePollers(
hub: AtomicHub,
subscribers: Subscribers,
subscription: Subscription,
pollers: MutableQueue.MutableQueue>
): void
/**
* Describes how publishers should signal to subscribers waiting for
* additional values from the hub that new values are available.
*/
unsafeCompleteSubscribers(
hub: AtomicHub,
subscribers: Subscribers
): void
}
/**
* A strategy that applies back pressure to publishers when the hub is at
* capacity. This guarantees that all subscribers will receive all messages
* published to the hub while they are subscribed. However, it creates the
* risk that a slow subscriber will slow down the rate at which messages
* are published and received by other subscribers.
*
* @internal
*/
class BackPressureStrategy implements HubStrategy {
publishers: MutableQueue.MutableQueue<
readonly [
A,
Deferred.Deferred,
boolean
]
> = MutableQueue.unbounded()
shutdown(): Effect.Effect {
return core.flatMap(core.fiberId, (fiberId) =>
core.flatMap(
core.sync(() => unsafePollAllQueue(this.publishers)),
(publishers) =>
fiberRuntime.forEachParUnboundedDiscard(
publishers,
([_, deferred, last]) =>
last ?
pipe(core.deferredInterruptWith(deferred, fiberId), core.asUnit) :
core.unit,
false
)
))
}
handleSurplus(
hub: AtomicHub,
subscribers: Subscribers,
elements: Iterable,
isShutdown: MutableRef.MutableRef
): Effect.Effect {
return core.withFiberRuntime((state) => {
const deferred = core.deferredUnsafeMake(state.id())
return pipe(
core.suspend(() => {
this.unsafeOffer(elements, deferred)
this.unsafeOnHubEmptySpace(hub, subscribers)
this.unsafeCompleteSubscribers(hub, subscribers)
return MutableRef.get(isShutdown) ?
core.interrupt :
core.deferredAwait(deferred)
}),
core.onInterrupt(() => core.sync(() => this.unsafeRemove(deferred)))
)
})
}
unsafeOnHubEmptySpace(
hub: AtomicHub,
subscribers: Subscribers
): void {
let keepPolling = true
while (keepPolling && !hub.isFull()) {
const publisher = pipe(this.publishers, MutableQueue.poll(MutableQueue.EmptyMutableQueue))
if (publisher === MutableQueue.EmptyMutableQueue) {
keepPolling = false
} else {
const published = hub.publish(publisher[0])
if (published && publisher[2]) {
unsafeCompleteDeferred(publisher[1], true)
} else if (!published) {
unsafeOfferAll(
this.publishers,
pipe(unsafePollAllQueue(this.publishers), Chunk.prepend(publisher))
)
}
this.unsafeCompleteSubscribers(hub, subscribers)
}
}
}
unsafeCompletePollers(
hub: AtomicHub,
subscribers: Subscribers,
subscription: Subscription,
pollers: MutableQueue.MutableQueue>
): void {
return unsafeStrategyCompletePollers(this, hub, subscribers, subscription, pollers)
}
unsafeCompleteSubscribers(hub: AtomicHub, subscribers: Subscribers): void {
return unsafeStrategyCompleteSubscribers(this, hub, subscribers)
}
private unsafeOffer(elements: Iterable, deferred: Deferred.Deferred): void {
const iterator = elements[Symbol.iterator]()
let next: IteratorResult = iterator.next()
if (!next.done) {
// eslint-disable-next-line no-constant-condition
while (1) {
const value = next.value
next = iterator.next()
if (next.done) {
pipe(
this.publishers,
MutableQueue.offer([value, deferred, true as boolean] as const)
)
break
}
pipe(
this.publishers,
MutableQueue.offer([value, deferred, false as boolean] as const)
)
}
}
}
unsafeRemove(deferred: Deferred.Deferred): void {
unsafeOfferAll(
this.publishers,
pipe(unsafePollAllQueue(this.publishers), Chunk.filter(([_, a]) => a !== deferred))
)
}
}
/**
* A strategy that drops new messages when the hub is at capacity. This
* guarantees that a slow subscriber will not slow down the rate at which
* messages are published. However, it creates the risk that a slow
* subscriber will slow down the rate at which messages are received by
* other subscribers and that subscribers may not receive all messages
* published to the hub while they are subscribed.
*
* @internal
*/
export class DroppingStrategy implements HubStrategy {
shutdown(): Effect.Effect {
return core.unit
}
handleSurplus(
_hub: AtomicHub,
_subscribers: Subscribers,
_elements: Iterable,
_isShutdown: MutableRef.MutableRef
): Effect.Effect {
return core.succeed(false)
}
unsafeOnHubEmptySpace(
_hub: AtomicHub,
_subscribers: Subscribers
): void {
//
}
unsafeCompletePollers(
hub: AtomicHub,
subscribers: Subscribers,
subscription: Subscription,
pollers: MutableQueue.MutableQueue>
): void {
return unsafeStrategyCompletePollers(this, hub, subscribers, subscription, pollers)
}
unsafeCompleteSubscribers(hub: AtomicHub, subscribers: Subscribers): void {
return unsafeStrategyCompleteSubscribers(this, hub, subscribers)
}
}
/**
* A strategy that adds new messages and drops old messages when the hub is
* at capacity. This guarantees that a slow subscriber will not slow down
* the rate at which messages are published and received by other
* subscribers. However, it creates the risk that a slow subscriber will
* not receive some messages published to the hub while it is subscribed.
*
* @internal
*/
export class SlidingStrategy implements HubStrategy {
shutdown(): Effect.Effect {
return core.unit
}
handleSurplus(
hub: AtomicHub,
subscribers: Subscribers,
elements: Iterable,
_isShutdown: MutableRef.MutableRef
): Effect.Effect {
return core.sync(() => {
this.unsafeSlidingPublish(hub, elements)
this.unsafeCompleteSubscribers(hub, subscribers)
return true
})
}
unsafeOnHubEmptySpace(
_hub: AtomicHub,
_subscribers: Subscribers
): void {
//
}
unsafeCompletePollers(
hub: AtomicHub,
subscribers: Subscribers,
subscription: Subscription,
pollers: MutableQueue.MutableQueue>
): void {
return unsafeStrategyCompletePollers(this, hub, subscribers, subscription, pollers)
}
unsafeCompleteSubscribers(hub: AtomicHub, subscribers: Subscribers): void {
return unsafeStrategyCompleteSubscribers(this, hub, subscribers)
}
unsafeSlidingPublish(hub: AtomicHub, elements: Iterable): void {
const it = elements[Symbol.iterator]()
let next = it.next()
if (!next.done && hub.capacity > 0) {
let a = next.value
let loop = true
while (loop) {
hub.slide()
const pub = hub.publish(a)
if (pub && (next = it.next()) && !next.done) {
a = next.value
} else if (pub) {
loop = false
}
}
}
}
}
/** @internal */
const unsafeStrategyCompletePollers = (
strategy: HubStrategy,
hub: AtomicHub,
subscribers: Subscribers,
subscription: Subscription,
pollers: MutableQueue.MutableQueue>
): void => {
let keepPolling = true
while (keepPolling && !subscription.isEmpty()) {
const poller = pipe(pollers, MutableQueue.poll(MutableQueue.EmptyMutableQueue))
if (poller === MutableQueue.EmptyMutableQueue) {
pipe(subscribers, removeSubscribers(subscription, pollers))
if (MutableQueue.isEmpty(pollers)) {
keepPolling = false
} else {
pipe(subscribers, addSubscribers(subscription, pollers))
}
} else {
const pollResult = subscription.poll(MutableQueue.EmptyMutableQueue)
if (pollResult === MutableQueue.EmptyMutableQueue) {
unsafeOfferAll(pollers, pipe(unsafePollAllQueue(pollers), Chunk.prepend(poller)))
} else {
unsafeCompleteDeferred(poller, pollResult)
strategy.unsafeOnHubEmptySpace(hub, subscribers)
}
}
}
}
/** @internal */
const unsafeStrategyCompleteSubscribers = (
strategy: HubStrategy,
hub: AtomicHub,
subscribers: Subscribers
): void => {
for (
const [subscription, pollersSet] of subscribers
) {
for (const pollers of pollersSet) {
strategy.unsafeCompletePollers(hub, subscribers, subscription, pollers)
}
}
}