Liking cljdoc? Tell your friends :D

API Reference

Namespace-by-namespace listing of all public functions and macros.

Naming convention: Sections below abbreviate org.replikativ.spindel.* to spindel.* for brevity. The real require is always the full org.replikativ.spindel.… form — see any file in src/ or examples/ for canonical require lines.

spindel.core

Convenience re-export namespace. All functions below are also available from their originating namespaces.

Macros

MacroDescription
(spin & body)Create a cached reactive spin with CPS transformation
(signal initial-value) / (signal ctx initial-value)Create a reactive signal with deterministic ID. The 2-arity form takes an explicit execution-context (e.g. (signal runtime [])) and is what top-level defs in the examples use.
(batch & body)Batch signal updates into a single propagation
(gen-aseq & body)Generate a lazy async sequence using yield
(for [bindings body])Async sequence comprehension with spindel effects

Effects

FunctionDescription
(await spin-or-deferred)Suspend until value available, track dependency
(track signal-ref)Read signal with dual perspective (new/old/deltas)
(yield value)Emit value in async sequence (inside gen-aseq)

Runtime

FunctionDescription
(create-execution-context & opts)Create root execution context
(fork-context parent & opts)Create O(1) forked context
(snapshot-context ctx & opts)Create immutable snapshot
(restore-snapshot ctx & opts)Restore snapshot to live context
(stop-context! ctx)Stop background drain thread
(serialize-context ctx)Serialize to EDN
(deserialize-context edn executor)Deserialize from EDN
(with-context ctx & body)Bind *execution-context* for body (CLJ macro)
(current-execution-context)Return bound context (throws if none)

Combinators

FunctionDescription
(parallel & spins)Execute concurrently, return vector of results
(race & spins)Return first to complete, cancel losers
(sleep ms) / (sleep ms val)Complete after delay
(timeout spin ms fallback)Race against deadline
(debounce source ms)Wait for quiet period
(throttle source hz merge-fn)Limit frequency
(sample source ms)Poll at fixed interval
(relieve source)Drop intermediate values
(accumulate signal merge-fn)Delta-preserving accumulation

Sync

FunctionDescription
(deferred)Create single-assignment deferred value
(deliver! d value)Deliver value from external context
(mailbox)Create FIFO message queue
(post! mbx msg)Post message from external context
(never)Spin that never completes
(spawn! spin) / (spawn! spin :on-error f)Fire-and-forget spin

Fork-Safe Atoms

FunctionDescription
(atom initial) / (atom initial :meta m)Create runtime atom (uses *execution-context*)
(create-atom initial & opts)Create with explicit options

Semaphore

FunctionDescription
(semaphore n)Create permit-based semaphore (uses *execution-context*)
(acquire sem)Spin completing on permit acquisition
(release sem)Release a permit
(holding sem spin)Run spin with permit held (try/finally)

Supervisor

FunctionDescription
(supervisor child-specs opts)Erlang-style supervisor spin (:one-for-one, :one-for-all, :rest-for-one)

Deltaable

FunctionDescription
(deltaable-vector v)Create delta-tracking vector
(deltaable-map m)Create delta-tracking map
(deltaable-set s)Create delta-tracking set

Pub/Sub

FunctionDescription
(mult source)Create fan-out mult
(tap mult buffer)Create tap on mult
(untap mult tap)Remove tap
(pub source topic-fn)Create topic-routed pub
(sub pub topic & opts)Subscribe to topic
(unsub pub topic sub)Unsubscribe
(partitioned n source partition-fn & opts)Hash-partitioned fan-out (n = power of 2)
(tap-partition p idx)Subscribe to one partition
(tap-all p)Subscribe to all partitions; returns vector
(fixed-buffer n)Fixed-size buffer
(dropping-buffer n)Dropping buffer
(sliding-buffer n)Sliding buffer

spindel.engine.core

Core engine bindings and state access functions.

Dynamic Vars

VarDescription
*execution-context*Current execution context (bind via with-context or binding)
*spin-id*Current spin ID during execution
*worker-id*Worker ID inside engine workers
*yield-handler*Yield handler for async sequence generation

Context Binding

FunctionDescription
(with-context ctx & body)Bind execution context for body (macro on CLJ, fn on CLJS)
(current-execution-context)Return bound context (throws if unbound)
(execution-context-bound?)Check if context is bound

State Access

FunctionDescription
(get-state path)Non-transactional read at path
(swap-state! path f)Atomically update state at path
(swap-state-args! path f & args)Atomically update with extra args
(cas-state! path old new)Compare-and-set at path

Spin Operations

FunctionDescription
(spin-register! spin-id meta)Register spin with runtime
(spin-mark-dirty! spin-id)Mark spin as dirty
(spin-cache-result! spin-id result)Cache result
(spin-current-result spin-id)Get cached result
(spin-result-clean? spin-id)Check if cached result is clean
(spin-result-dirty? spin-id)Check if cached result is dirty
(current-spin-id)Get current spin ID
(spin-is-cancelled?)Check if current spin is cancelled

Dependency Tracking

FunctionDescription
(deps-track-signal! spin-id signal-id)Record signal dependency
(deps-track-spin! parent child)Record spin dependency
(graph-commit-deps! spin-id)Commit tracked dependencies
(graph-clear-deps! spin-id)Clear spin from graph
(graph-ordered-observers signal-id)Get ordered observer list

Continuation Operations

FunctionDescription
(continuation-add! spin-id cont)Add continuation (auto-captures bindings)
(continuation-remove! spin-id cont-id)Remove continuation
(continuation-earliest spin-id signal-id)Get earliest continuation
(continuation-resume! spin-id cont resume-fn)Resume continuation

Scheduling

FunctionDescription
(get-executor)Get executor for spin scheduling
(schedule-spin-execution! spin-fn)Schedule spin for execution
(schedule-delayed-execution! ms spin-fn)Schedule after delay
(enqueue-event! event)Enqueue engine event
(make-handler ctx handler-fn)Create auto-binding event handler

spindel.engine.context

Execution context lifecycle management. See Forking for usage guide.

Creation

FunctionDescription
(create-execution-context & opts)Create root context
(fork-context parent & opts)Create O(1) fork with overlay
(create-simulation-context & opts)Create deterministic test context

Lifecycle

FunctionDescription
(stop-context! ctx)Stop drain thread (no-op on forks)
(close-context! ctx)Stop drain + close executor

Accessors

FunctionDescription
(root-context? ctx)True if root (no parent)
(fork-depth ctx)Fork depth (0 for root)
(get-fork-id ctx)Fork ID
(get-parent-ctx ctx)Parent context (nil for root)
(get-metadata ctx)Fork metadata
(get-executor ctx)Executor
(get-bindings ctx)Fork-local bindings

Execution Mode

FunctionDescription
(get-execution-mode ctx)Get mode (nil, :normal, :rebuild)
(set-execution-mode ctx mode)Return new context with mode set
(rebuild-mode? ctx)True if in rebuild mode

Snapshot & Serialization

FunctionDescription
(snapshot-context ctx & opts)Create immutable snapshot
(restore-snapshot ctx & opts)Restore to live context
(serialize-context ctx)Serialize to EDN string
(deserialize-context edn executor)Deserialize from EDN

Rebuild

FunctionDescription
(prepare-rebuild-context ctx & opts)Prepare for rebuild
(finalize-rebuild-context ctx & opts)Finalize after rebuild
(with-rebuild-context ctx opts & body)Execute body in rebuild mode

Virtual Time

FunctionDescription
(get-time-mode ctx):virtual or :real
(set-time-mode! ctx mode)Set time mode
(current-time ctx)Current time (virtual or real)
(advance-time! ctx ms)Advance virtual time, process events

Fork Lineage

FunctionDescription
(get-process-id ctx)Elle-compatible process ID
(get-parent-process-id ctx)Parent's process ID
(get-fork-lineage ctx)Vector of process IDs root→current

spindel.signal

Reactive signals with delta tracking.

Function/MacroDescription
(signal initial-value) / (signal ctx initial-value)Create signal with deterministic ID (macro). 2-arity form takes an explicit execution-context, used at top-level defs.
(batch & body)Batch signal updates (macro)
(deref-signal sig)Non-reactive deref
(get-signal-value sig)Read current value
(get-signal-state sig)Get full signal state
(get-signal-detailed sig)Get value as Interval
(clear-signal-deltas! sig)Clear consumed deltas
(swap-signal-changed? sig f & args)Swap and return changed?
(signal-interval value)Create Interval from value
(ensure-signal-initialized! sig)Initialize signal in runtime

Signals implement IDeref (@), IAtom (swap!, reset!).


spindel.atom

Fork-safe atoms stored in the execution context.

FunctionDescription
(atom initial-value & opts)Create atom (uses *execution-context*)
(create-atom initial-value & opts)Create atom with explicit context

Atoms implement IDeref (@), IAtom (swap!, reset!), IRef (add-watch, remove-watch).


spindel.semaphore

Fork-safe semaphores for concurrent access control.

FunctionDescription
(semaphore max-permits)Create semaphore (uses *execution-context*)
(create-semaphore ctx max-permits)Create with explicit context
(acquire sem)Returns spin completing on permit acquisition
(release sem)Release permit, wake next waiter
(holding sem spin)Execute spin with permit (auto-release)

Semaphores implement IDeref (@sem returns available permits).


spindel.spin.core

Spin type, lifecycle, and error handling.

Spin Type

FunctionDescription
(make-spin spin-fn)Create spin with generated ID
(make-spin spin-fn spin-id)Create spin with explicit ID
(register-cleanup! obj cleanup-fn)Register GC cleanup

Result Type

FunctionDescription
(ok value)Create success result
(error err)Create error result
(ok? result)True if success
(error? result)True if error
(unwrap result)Get value or throw
(match result ok-fn err-fn)Pattern match on result

Error Handling

FunctionDescription
(attempt spin)Capture errors as functions
(absolve spin)Unwrap captured errors
(cancel-spin! spin)Cancel spin and observers
(spin-cancelled? spin)Check if cancelled
(spin-failed? spin)Check if failed
(cleanup-spin! spin)Manually remove from runtime
(abort-spin-chain! spin-id err)Abort spin and observers

CPS Helpers

FunctionDescription
(resume cont-fn value)Resume continuation (handles trampolining)

Constants

ConstantDescription
incompleteSentinel for suspended spin
spin-cancelledCancellation marker

spindel.spin.cps

CPS transformation macros.

MacroDescription
(spin & body)Create cached reactive spin with CPS transformation
(effect & body)Create effect-only spin (for side effects, returns nil)

spindel.spin.combinators

Spin composition and rate control. See Combinators.

FunctionDescription
(parallel & spins)Execute concurrently, return vector
(race & spins)First to complete wins
(sleep ms) / (sleep ms val)Time delay
(timeout spin ms fallback)Deadline with fallback
(debounce source ms)Quiet period
(throttle source hz merge-fn)Max frequency
(sample source ms)Fixed interval polling
(relieve source)Drop intermediate values
(accumulate signal merge-fn)Delta-preserving accumulation

spindel.spin.sync

Synchronization primitives.

FunctionDescription
(deferred)Create single-assignment deferred
(create-deferred ctx)Create with explicit context
(deliver! d value)Deliver from external context
(mailbox)Create FIFO message queue
(create-mailbox ctx)Create with explicit context
(post! mbx msg)Post from external context
(never)Spin that never completes
(spawn! spin) / (spawn! spin :on-error f)Fire-and-forget execution

spindel.spin.supervisor

Erlang-style supervision for spawned spins.

FunctionDescription
(supervisor child-specs opts)Returns a spin that supervises children

child-specs is a vector of {:id keyword :start (fn []) ...} maps where :start returns a fresh spin on each restart.

opts keys:

KeyDescription
:strategy:one-for-one, :one-for-all, or :rest-for-one
:max-restartsMax restart budget per window (default 3)
:window-msWindow for the restart budget (default 60000)
:on-fatalCallback (fn [reason]) when budget is exhausted

spindel.effects.await

FunctionDescription
(await spin-or-deferred)Suspend until value available
(await-handler awaitable spin-id loc resolve reject)Direct handler
(reactive-spin? x)True if x is a Spin

spindel.effects.track

FunctionDescription
(track signal-ref)Read signal with dual perspective
(track-handler trackable spin-id loc resolve reject)Direct handler
(signal-ref? x)True if x is a SignalRef

spindel.effects.yield

FunctionDescription
(yield value)Emit value in async sequence

spindel.engine.effects

Effect registration system.

FunctionDescription
(register-effect-by-symbol! sym handler adapter)Register effect
(register-effect-by-symbol! sym handler adapter direct-sym)Register with direct handler
(get-effect-syntax)Get effect registry map
(dispatch-symbol-call ctx sym args spin-id loc resolve reject)Dispatch effect
(check-cancellation! spin-id)Check/throw if cancelled
(one-arg->awaitable-map args)Standard adapter: (effect x) to {:awaitable x}
(type-error effect-name expected actual)Create type error

Protocol: PEffectHandler

(handle-effect [this context args resolve reject])

spindel.seq.core

Async sequence generation and consumption.

Function/MacroDescription
(gen-aseq & body)Generate lazy async sequence (macro)
(for [bindings body])Async comprehension (macro)
(yield value)Emit value in gen-aseq
(anext seq)Get next [value rest] or nil
(into coll seq)Collect all into collection

spindel.incremental.deltaable

Delta-tracking collections. See Incremental.

FunctionDescription
(deltaable-vector v)Wrap vector
(deltaable-map m)Wrap map
(deltaable-set s)Wrap set
(deltaable-value v)Wrap simple value
(get-deltas x)Get accumulated deltas
(has-deltas? x)True if non-empty deltas
(clear-deltas x)Return copy with deltas cleared
(wrap-deltaable x)Wrap as deltaable (shallow)
(unwrap-deltaable x)Unwrap to plain collection
(unwrap x)Get raw value
(apply-delta coll delta)Apply single delta to collection
(compact-deltas deltas)Remove redundant operations
(merge-deltas & seqs)Concatenate delta sequences
(transduce-deltas xf init deltas)Transduce deltas
(map-delta f)Delta transducer: transform values
(filter-delta pred)Delta transducer: filter with enter/exit
(remove-delta pred)Delta transducer: inverse filter
(keep-delta f)Delta transducer: transform + filter

spindel.incremental.interval

Interval abstraction for incremental computation.

FunctionDescription
(interval new) / (interval old new) / (interval old new deltas)Create interval
(interval? x)Type check
(as-interval x)Coerce to interval
(as-interval-with-old prev current)Coerce with previous baseline
(changed? iv)True if old != new
(static? iv)True if no old and no deltas
(derive-interval prev-output new deltas)Create derived interval
(merge-intervals acc new)Merge intervals (associative)

Protocol: PInterval

(get-old this)     ;; baseline value
(get-new this)     ;; current value
(get-deltas this)  ;; delta sequence
(has-deltas? this) ;; true if pending
(commit this)      ;; end interval (new→old, clear deltas)

spindel.incremental.combinators

Incremental operations on intervals.

All combinators return a typed-interval map {:algebra A :old :new :deltas} — see Incremental Collections for the algebra contract.

MacroDescription
(ifilter pred source)Incremental filter (sequence algebra)
(imap f source)Incremental map (sequence algebra)
(ireduce rf init source)Incremental reduce (scalar algebra)
(ifor-each key-fn transform source)Keyed per-item transformation (sequence algebra)
(islice window source)Windowed view for virtual scroll (sequence algebra). window is a map {:start n :end n}.
(izip f s1 s2 …)Combine intervals into a scalar (typed combinator)
(iflat-map f source)Flat-map producing a sequence interval (typed combinator)

spindel.dom.elements

vnode constructors. The el/* macros (el/div, el/span, el/h1, …) are generated for every HTML tag.

Macro / FnDescription
(el/<tag> attrs? & children)One macro per HTML tag — emits a vnode at a deterministic addr derived from source location.
(el/text s)Text vnode (auto-wrapped when a string appears as a child).
(el/fragment & children)Inline fragment vnode (children spliced into parent).

Common vnode attrs: :class, :style, :id, any :data-*, event handlers as :on-click / :on-input / …, and:

  • :key — stable identity within an ifor-each fragment.
  • :ref(fn [el-or-nil] …) called on mount with the live DOM element and on unmount with nil. Not re-fired on reconcile (the element identity survives). See examples/block_editor_demo and examples/README.md for the canonical usage pattern.

spindel.dom.foreach

Typed-sequence to DOM bridge. Emits a single :seq-diff child delta carrying a SequenceAlgebra record.

Macro / FnDescription
(ifor-each key-fn source render-fn)(macro) Render an interval of items as a keyed fragment under the surrounding parent. Source can be a signal, an interval, or any value implementing PInterval.
(for-each* …)(fn) Underlying functional form used by the macro.

Wrapping rule: the ifor-each fragment must be the sole child of its parent element. apply-seq-diff! (dom/discharge.cljc:418-497) walks (range size-after) and passes those indices straight into insert-child! / move-child! / remove-child!, which interpret them as positions in parent.childNodes. With sibling DOM nodes preceding the fragment the indices skew by the sibling count and the diff corrupts on update. The workaround until the discharge takes an :offset is structural: wrap the ifor-each in its own <div> / <ul> and put headings, footers, separators one level up.

spindel.dom.foreign

Macro / FnDescription
(foreign-node attrs)(macro) Escape hatch for third-party JS that owns its subtree (TipTap, ProseMirror, video, …). Accepts :on-mount, :on-unmount callbacks. Spindel manages the container, the third-party lib manages everything inside.
(foreign-node* loc attrs)(fn) Underlying form.

spindel.dom.discharge

PDischarge protocol — implemented by browser/make-dom-discharge for real DOM and by examples.shared.logging-discharge for diagnostic op logging. Users typically don't implement this protocol — they wrap the browser discharge for logging or build a server-side string implementation.

FunctionDescription
(make-mock-discharge)Returns {:discharge :log} — a mock implementation for unit tests.
apply-seq-diff!Internal: consumes a SequenceAlgebra :seq-diff and applies grow → permutation → shrink → change → freeze to DOM children.

spindel.dom.render

FunctionDescription
(render-spin! container spin discharge)Mount a spin's vnode output into container and wire reactive re-render on signal changes. Returns {:stop! fn :state atom}.
(render-once! container vnode discharge)One-shot non-reactive render.
(create-render-effect container discharge)Lower-level: returns a function that takes a vnode and discharges to container, with :applied-vnodes cross-cycle deduplication.

spindel.pubsub.mult

Fan-out broadcasting. See Pub/Sub.

FunctionDescription
(mult source-aseq)Create mult
(tap mult) / (tap mult buffer) / (tap mult buffer close?)Create tap
(untap mult tap)Remove tap
(mult-pump mult)Get pump spin
(mult-closed? mult)True if source exhausted
(tap-closed? tap)True if tap closed

spindel.pubsub.pub

Topic-based routing.

FunctionDescription
(pub source topic-fn) / (pub source topic-fn buf-fn)Create pub
(sub pub topic) / (sub pub topic buffer) / (sub pub topic buffer close?)Subscribe
(unsub pub topic tap)Unsubscribe
(unsub-all pub)Unsubscribe all topics
(pub-closed? pub)True if source exhausted

spindel.pubsub.partitioned

Hash-partitioned fan-out (Rama-style). The source is routed to one of N partitions (N must be a power of two) using a partition-fn that extracts a routing key. Each partition has its own buffer; consumers tap individual partitions for parallel downstream processing.

FunctionDescription
(partitioned n source partition-fn & opts)Create with N partitions
(tap-partition p idx) / (tap-partition p idx buffer)Subscribe to one partition
(tap-all p)Subscribe to every partition; returns a vector of taps
(partition-post! p idx item)Post directly to a partition (e.g. for chained pipelines)
(close! p)Close all partitions
(closed? p)True if closed

opts:

KeyDescription
:buf-fn(fn [partition-idx] buffer) factory; default fixed-buffer 64

spindel.pubsub.buffer

Buffer implementations.

FunctionDescription
(fixed-buffer n)Blocks when full
(dropping-buffer n)Never blocks, drops new
(sliding-buffer n)Never blocks, drops oldest
(full? buf)True if at capacity
(buffer-empty? buf)True if no items
(unblocking? buf)True if never blocks

Protocol: PBuffer

(full? buffer)      ;; capacity check
(add! buffer item)  ;; enqueue
(remove! buffer)    ;; dequeue oldest
(close-buf! buffer) ;; cleanup

spindel.sci.boundary

SCI integration — functional API. See SCI Integration.

FunctionDescription
(create-spindel-sci-context opts)Create SCI context with spindel support
(wrap-spin-for-sci task runtime)Wrap native spin as BoundaryTask
(make-spin-for-sci spin-fn id runtime)Create spin from SCI context

Options for create-spindel-sci-context

KeyTypeDefaultDescription
:runtimeExecutionContextrequiredExecution context
:expose-runtime-state?booleanfalseExpose state access
:native-spinsmap{}{sym → spin} auto-wrapped

spindel.sci.macro

SCI integration — full macro support.

FunctionDescription
(create-spin-macro-context opts)Create SCI context with spin macro
(eval-spin sci-ctx code-str)Evaluate, return Spin
(eval-and-deref sci-ctx code-str)Evaluate and deref

Options for create-spin-macro-context

KeyTypeDefaultDescription
:runtimeExecutionContextrequiredExecution context
:native-spinsmap{}{sym → spin} auto-wrapped
:expose-track?booleantrueInclude track effect

spindel.sci.core

SCI support utilities.

FunctionDescription
(load-partial-cps! sci-ctx)Load CPS runtime into SCI
(common-classes)Standard class allowlist for SCI

spindel.distributed.core

Distributed computing bridge.

Spin/Channel Conversion

FunctionDescription
(spin->chan spin)Convert spin to core.async channel
(chan->spin ch)Convert channel to spin

Context Registry

FunctionDescription
(register-context! id ctx)Register context for remote access
(unregister-context! id)Remove context
(get-context id)Look up context
(list-contexts)List registered IDs

Remote Spin Registry

FunctionDescription
(register-remote-spin! name factory)Register remote spin factory
(get-remote-spin name)Look up factory

Peer Management

FunctionDescription
(set-system-peer! peer)Set kabel peer
(get-system-peer)Get current peer

Response Handling

FunctionDescription
(register-response-handler! id callback)Register response callback
(unregister-response-handler! id)Remove handler
(get-response-handler id)Look up handler
(handle-response! response)Dispatch response

spindel.distributed.macros

Distributed function definition.

MacroDescription
(defn-spin-remote name [params] & body)Define distributed function
(spin-remote scope [explicit-args] & body)Execute body on remote peer

scope is either a peer-id or [peer-id context-id].

All free variables in spin-remote body must be declared in the explicit args vector (compile-time validation).

Can you improve this documentation?Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
Move to previous article
Move to next article
Ctrl+/Jump to the search field
× close