Skip to content

Run the engine off the main thread ​

Use this page when a recalculation must not block a UI or a server's event loop, or when several workbooks should calculate at the same time. A Workbook belongs to the thread or worker that created it, so concurrency comes from giving each worker its own engine and its own workbooks and passing workbook bytes between them. Workbook lifecycle states the threading rules, WebAssembly covers the two npm entries, and Python covers the wheel's process model.

Calculate in a Node worker thread ​

Each node:worker_threads worker imports the package and calls createFormulon() itself; a workbook handle cannot cross to another thread. Send the workbook as bytes: wb.save() returns a Uint8Array that owns its buffer, so it can go in the transfer list and move to the worker without a copy.

js
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads'
import createFormulon from '@libraz/formulon'

if (isMainThread) {
  const formulon = await createFormulon()
  const wb = formulon.Workbook.createDefault()
  let bytes
  try {
    const ws = wb.sheet(0)
    ws.setValues('A1', Array.from({ length: 1000 }, (_, i) => [i + 1]))
    ws.setFormula('B1', '=SUM(A1:A1000)')
    bytes = wb.save()
  } finally {
    wb.dispose()
  }

  const worker = new Worker(new URL(import.meta.url), { workerData: bytes, transferList: [bytes.buffer] })
  const result = await new Promise((resolve, reject) => {
    worker.once('message', resolve)
    worker.once('error', reject)
  })
  console.log(result.total) // 500500
  console.log(bytes.byteLength) // 0
} else {
  const formulon = await createFormulon()
  const wb = formulon.Workbook.load(workerData)
  try {
    parentPort.postMessage({ total: wb.sheet(0).getValue('B1') })
  } finally {
    wb.dispose()
  }
}

After the transfer the sender's array is detached, which the zero length shows. A worker that serves many requests keeps its Formulon object and loads a new workbook per request, disposing each one when done.

Keep a browser page responsive ​

In a browser, put the engine in a module Web Worker and talk to it with messages. The default @libraz/formulon build is single-threaded and needs no special server headers. The worker below, worker.js, keeps one workbook open and answers edit and read requests, so the page never waits on a recalculation. Upload, recalculate and download shows the one-shot variant that recalculates an uploaded file. The two files below need a browser page, so they are type-checked but not executed.

js
// worker.js
import createFormulon from '@libraz/formulon'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)

self.onmessage = (event) => {
  const { id, op, cell, value } = event.data
  try {
    if (op === 'set') ws.setValue(cell, value)
    self.postMessage({ id, ok: true, value: op === 'get' ? ws.getDisplayText(cell).text : null })
  } catch (e) {
    self.postMessage({ id, ok: false, message: e instanceof Error ? e.message : String(e) })
  }
}

The page creates the worker and turns each request into a promise:

js
// main.js
const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' })
const pending = new Map()
let nextId = 0

worker.onmessage = (event) => {
  const { id, ok, value, message } = event.data
  const request = pending.get(id)
  pending.delete(id)
  if (ok) request.resolve(value)
  else request.reject(new Error(message))
}

/**
 * @param {'set' | 'get'} op
 * @param {string} cell
 * @param {unknown} [value]
 */
function call(op, cell, value) {
  const id = nextId++
  return new Promise((resolve, reject) => {
    pending.set(id, { resolve, reject })
    worker.postMessage({ id, op, cell, value })
  })
}

await call('set', 'A1', 2)
await call('set', 'B1', '=A1*21')
document.title = String(await call('get', 'B1'))

The worker handles one message at a time, so two callers never use the workbook at once.

Use the threads build ​

@libraz/formulon/threads is the pthread build: wb.recalcParallel(threadCount) spreads one workbook's recalculation over up to eight workers it starts itself, and returns statistics once they have joined. The results are the same as recalc(). On the default build recalcParallel runs serially and reports workerThreadsStarted: 0, so the same code runs on both. In Node the threads build needs nothing extra.

js
import createFormulon from '@libraz/formulon/threads'

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  const ws = wb.sheet(0)
  ws.setValues('A1', Array.from({ length: 2000 }, (_, i) => [i]))
  for (let row = 0; row < 2000; row++) ws.setFormula(row, 1, `=A${row + 1}*2+SUM(A1:A${row + 1})`)

  const stats = wb.recalcParallel(2)
  console.log(stats.cellsEvaluated) // 2000
  console.log(stats.workerThreadsStarted <= 2) // true
  console.log(ws.getValue('B2000')) // 2002998
} finally {
  wb.dispose()
}

In a browser the threads build shares the WebAssembly heap with its workers through SharedArrayBuffer, which a page has only when it is cross-origin isolated. Serve the page with these two headers, and make every sub-resource same-origin or send it with a Cross-Origin-Resource-Policy header:

text
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

A page that may be served without them can choose the build at run time. This example reads crossOriginIsolated, which only a browser page sets, so it is type-checked but not executed:

js
const { default: createFormulon } = globalThis.crossOriginIsolated
  ? await import('@libraz/formulon/threads')
  : await import('@libraz/formulon')

const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
  wb.sheet(0).setFormula('A1', '=SUM(1,2)')
  const stats = wb.recalcParallel(0)
  console.log(`workers: ${stats.workerThreadsStarted}`)
} finally {
  wb.dispose()
}

A bundler must emit ES module workers for the threads build; WebAssembly has the Vite setting and the full header requirements. @libraz/formulon-native and the CLI's recalc --threads run the same parallel scheduler without any of this.

Use threads and processes in Python ​

The wheel runs one WebAssembly instance per process, and calls into it are serialized. Python threads may each use their own workbooks safely, but they take turns, so they do not calculate faster. For parallel calculation use processes, each with its own workbooks. A Workbook object does not cross a process boundary, so pass file paths or the bytes from wb.save(). A process also keeps the memory its instance has grown until it exits, so recycling worker processes (max_tasks_per_child on Python 3.11 and later) returns it.

python
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

from formulon import Workbook


def build(n):
    with Workbook.create_default() as wb:
        ws = wb[0]
        ws.set_values("A1", [[i] for i in range(1, n + 1)])
        ws.set_formula("B1", f"=SUM(A1:A{n})")
        return wb.save()


def total(data):
    with Workbook.load(data) as wb:
        return wb[0]["B1"]


if __name__ == "__main__":
    books = [build(n) for n in (10, 100, 1000)]

    with ThreadPoolExecutor(max_workers=2) as pool:
        print(list(pool.map(total, books)))  # [55.0, 5050.0, 500500.0]

    with ProcessPoolExecutor(max_workers=2) as pool:
        print(list(pool.map(total, books)))  # [55.0, 5050.0, 500500.0]

A trap inside the WebAssembly instance makes every workbook in that process unusable, which is one more reason to keep long batch jobs in worker processes that can be replaced.