Skip to content

feat(js): replace otto with grafana/sobek JavaScript engine (otto→sobek phase 1) - #5141

Open
TomOnTime wants to merge 11 commits into
mainfrom
tlim_sobek_phase1
Open

TomOnTime wants to merge 11 commits into
mainfrom
tlim_sobek_phase1

Conversation

@TomOnTime

@TomOnTime TomOnTime commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Issue

This is phase 1 of switching from otto to sobek as our JavaScript interpreter. Phase 0 added tests. Phase 2 will do cleanups.

Resolution

otto fully replaced by sobek.

What users will notice:

  • Modern JavaScript works in dnsconfig.js: let/const, arrow functions, template strings, classes and async/await.
  • Errors give the file, line and column. I strip sobek's internal noise from the messages.
  • It's about 4× faster: 0.28 s instead of 1.12 s for check on the large config.
  • The release binary is 4.8 MB larger (+3.7%).

Notes

Phase 1 of #5135. dnsconfig.js now runs on grafana/sobek instead of robertkrimen/otto + xddxdd/ottoext. Both of those are removed from go.mod.

Equivalence

What changed

Area Before (otto/ottoext) Now
Engine otto (ES5) sobek (ES2015+)
Timers ottoext/timers + ottoext/loop pkg/js/eventloop.go: one goroutine, a timer heap, async completions delivered over a channel. Same minimum delays (4 ms, and 10 ms for intervals). Includes setImmediate.
Promises ottoext/promise (a JS polyfill) native
fetch() (--allow-fetch) ottoext/fetch pkg/js/fetch.go + fetch.js: the same Headers/Request/Response API with the same quirks (ok is always true, statusText is like "200 OK", type is undefined). The HTTP request runs on a goroutine and the Promise is resolved on the loop.
underscore _ embedded by otto pkg/js/underscore-min.js (1.13.7, the same file) plus its MIT license. Still available to user scripts, but deprecated: see below.
Record filepos parsed from the text of new Error().stack (helpers.js said "this will certainly break if we change to a different Javascript interpreter") _filepos(), written in Go, reads the outermost frame from sobek's call stack. sobek sometimes reports a call at its (, so the column is moved back to the start of the callee, which is what otto reported.

Things found along the way

  • helpers.js has always started with "use strict", but otto ignored it. sobek enforces it, and 20 assignments to undeclared variables threw ReferenceError (in TTL("1h"), SPF_BUILDER, CAA_BUILDER, LOC_BUILDER_*, …). I declared them with var. SPF_BUILDER/CAA_BUILDER used to set the globals r and p, which overwrote any user variables with those names.
  • Three of those functions (getENotationInt, locStringBuilder, locDMSBuilder) are dead code, because LOC is built in Go. I deleted them rather than make them strict-safe.
  • New strict_test.go parses helpers.js with sobek's parser and fails on any assignment to a variable that isn't declared in scope. In strict mode those only throw when the line runs, so ordinary tests can miss them.
  • The REVCOMPAT bad mode test from Phase 0 only passed because of test order: the mode is process-wide and can be set once. It now just requires an error. go test -race -count=5 ./pkg/js passes.
  • The ottoext clearTimeout data race no longer exists, so the Phase 0 race skips are removed.

User-visible changes (suggested release note)

  • dnsconfig.js can use modern JavaScript: let/const, arrow functions, template literals, destructuring, spread, classes, async/await, Array.prototype.includes, Object.entries, and full JS regular expressions, including lookahead. otto rejected these.

  • Errors now say where the problem is:

    Problem otto sobek
    Syntax error (anonymous): Line 4:1 Unexpected end of input SyntaxError: Unexpected end of input at syntax.js:4:1
    Undefined name ReferenceError: 'AA' is not defined ReferenceError: AA is not defined at undefined.js:2:25
    throw in a user script custom problem custom problem at throwstr.js:2:1
    Error in a required file File throws.js: ReferenceError: 'undefinedThing' is not defined File throws.js: ReferenceError: undefinedThing is not defined at f (throws.js:2:10)

    sobek's bytecode offsets (:2:25(12)), Go frame names (at github.com/…require-fm (native)) and a doubled SyntaxError: prefix are stripped (cleanJSError).

  • Records created inside setTimeout/Promise callbacks now get a real filepos. otto reported <unknown>.

  • About 4× faster. The 29,000-line config takes 0.28 s for check, down from 1.12 s.

underscore.js deprecation (#5142)

  • _ is now a Proxy around underscore. The first time a config uses it (reading a property like _.each, or calling _(list)), dnscontrol prints this once per run:

    WARNING: dnsconfig.js uses _ (underscore.js), which is deprecated and will be removed in a release on or after 2028-11-29. Use plain JavaScript instead; see https://docs.dnscontrol.org/advanced-features/code-tricks

  • typeof _ doesn't trigger it, and neither do helpers.js or fetch. Configs that don't use _ see nothing, and _ itself behaves exactly as before.
  • The warning goes to stderr. printer writes to stdout, which would have put the warning in front of the JSON from print-ir > ir.json.
  • Docs: the code-tricks.md loop example uses forEach instead of _.each, and a new "Replacing underscore.js" section lists plain JavaScript equivalents.
  • Suggested release note: "_ (underscore.js) in dnsconfig.js is deprecated and will be removed in a release on or after 2028-11-29. DNSControl now prints a warning when a configuration uses it. See "Replacing underscore.js" in the docs."
  • Tests: TestUnderscoreDeprecationWarning (once per run; not for typeof, helpers, or configs without _; also inside callbacks).

Costs

  • The stripped release binary grows from 128.3 MB to 133.1 MB (+4.8 MB, +3.7%). sobek brings in dlclark/regexp2/v2, go-sourcemap, and google/pprof as indirect dependencies.

Left for Phase 2 (#5135)

  • Fixing the fetch quirks (ok, statusText, type). These would be behavior changes.
  • Unhandled Promise rejections are still ignored, as before. Making them errors would be a behavior change.
  • Replace the globals currentDirectory/configDirectory with per-run state. PANIC still calls os.Exit.
  • Document ES2015+ support, e.g. documentation/getting-started/typescript.md still recommends "lib": ["es5"].
  • Delete validateIntegers in helpers.js, which is also unused.

Testing

  • go test ./... passes
  • go test -race -count=5 ./pkg/js passes
  • golangci-lint run ./pkg/js/... ./commands/... reports 0 issues
  • prettier check passes on helpers.js and fetch.js
  • New tests: TestUnderscoreDeprecationWarning, TestModernSyntax, TestFilePos, TestErrorsNameTheFile, TestCleanJSError, TestHelpersNoUndeclaredAssignments

🤖 Generated with Claude Code

…ek phase 1)

Phase 1 of #5135. dnsconfig.js now runs on github.com/grafana/sobek
instead of github.com/robertkrimen/otto + github.com/xddxdd/ottoext.

* pkg/js/js.go, hash.go: port the runtime and Go builtins to sobek.
* pkg/js/eventloop.go: a small event loop for setTimeout, setInterval,
  setImmediate and their clear functions, and for completing async Go
  work on the runtime's goroutine. Promises are native to sobek.
* pkg/js/fetch.go, fetch.js: fetch() (with --allow-fetch), with the
  same API and quirks as ottoext's.
* pkg/js/underscore-min.js: underscore.js 1.13.7 (MIT, with its
  license), previously embedded by otto, stays available as _.
* helpers.js: record filepos now comes from _filepos(), which reads
  sobek's call stack, instead of parsing otto's Error().stack text.
  The positions are unchanged.
* helpers.js is in strict mode, which otto ignored and sobek enforces.
  Declare the locals it assigned without var, and delete
  getENotationInt, locStringBuilder and locDMSBuilder, which were
  unused (LOC is built in Go). strict_test.go checks helpers.js for
  assignments to undeclared variables.
* Tidy engine error messages: drop sobek's bytecode offsets and Go
  frame names, and a doubled "SyntaxError:" prefix.

The IR produced for every parse test, and for a 29,000-line config,
is byte-for-byte identical to otto's. That config is about 4x faster.

User-visible changes: dnsconfig.js may use ES2015+ (let/const, arrow
functions, template literals, classes, async/await, ...) and full
JavaScript regular expressions; most errors now say the file, line and
column; records made in timer or Promise callbacks get a real filepos
instead of "<unknown>".
otto's JSON.stringify wrote object keys in sorted order; sobek writes
them in the order the config declares them, as JavaScript requires.
Provider metadata (NewRegistrar, NewDnsProvider and SERVICE options)
is kept as raw JSON, so print-ir showed nested keys such as BIND's
default_soa in a different order than before.

Sort the keys of that raw JSON after reading the config. Numbers keep
their exact text, and "&" and "<" are not escaped.

TestParsedFiles compares decoded JSON, so it cannot see key order; add
TestMetadataKeysSorted, which checks the raw bytes, and a parse test
with unsorted nested metadata.
TomOnTime added a commit that referenced this pull request Nov 29, 2026
…5144)

Prep for #5141 (otto→sobek, #5135).

## Problem
Provider metadata (the options passed to `NewRegistrar`,
`NewDnsProvider` and `SERVICE`) is stored in the IR as the raw JSON that
`JSON.stringify` produces, so its key order depends on the JavaScript
engine:
- **otto** (current) writes object keys in sorted order.
- **sobek** (#5141) keeps the order the config uses, as the JavaScript
spec requires.

On a real config, `print-ir` from the sobek build therefore showed
BIND's `default_soa` keys in a different order (`… retry, expire,
minttl` instead of `expire, …, minttl, …, retry`). The values were
identical.

## Fix
`sortMetadataKeys` (in `pkg/js/js.go`) sorts the keys of that raw JSON
at every level after the config is read. Numbers keep their exact text
(`UseNumber`), `&` and `<` stay unescaped, and arrays keep their order.

**With otto this changes nothing.** It makes the existing behavior
explicit, so #5141 keeps the IR identical.

## Tests
- `TestMetadataKeysSorted` checks the **raw bytes** of registrar,
provider and per-domain (`SERVICE`) metadata. `TestParsedFiles` can't
catch this, because it compares decoded JSON. On the sobek branch, this
test fails without the fix and passes with it.
- New parse test `075-provider-meta-key-order`, with unsorted nested
metadata.
- `TestSortJSONKeys` covers nesting, number text, HTML characters and
arrays.
- `go test ./pkg/js` passes and `golangci-lint run ./pkg/js/...` reports
0 issues.

After this merges, I'll update #5141 from `main` and drop its copy of
this change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
… otto"

This reverts commit 6c283d8. The same fix was merged to main
separately in #5144 and comes back with the merge from main.
Deprecate underscore.js (#5142). After loading it, replace the global _
with a Proxy that prints a warning the first time a config uses it
(reads a property, as in _.each, or calls it, as in _(list)); typeof _
does not count. _ keeps working as before. It will be removed in a
release on or after 2028-11-29.

The warning goes to stderr, not the printer (stdout), so that
"print-ir > ir.json" still writes valid JSON.

Docs: the code-tricks.md loop example now uses forEach instead of
_.each, and a new "Replacing underscore.js" section lists plain
JavaScript equivalents. The warning links to that page.
TomOnTime and others added 4 commits December 1, 2026 17:08
Reported in #4371: otto provided a console object and let `this` reach
the global object in strict-mode functions; sobek does neither.

- Add a console object matching otto's (log/debug/info/warn/error print
  to stdout; dir/time/timeEnd/trace/assert are no-ops).
- CLI_DEFAULTS uses globalThis instead of `this`, which is undefined in
  strict mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant