Commit Graph

341 Commits

Author SHA1 Message Date
Anders Eknert 037101cd7c Linter configuration cleanup (#8397)
And enable more staticcheck linters. I saw staticcheck failures
mentioned in another PR, so thought I'd check it out.

- `WriteString(fmt.Sprintf)` -> `fmt.Fprintf`
- Rewrite calls to deprecated `*Rule.Path()`
- Don't use `==` to compare `time.Time`
- Use inline ignores over config exclusions of paths
- Remove 'varcheck' ignores as no longer used
- Remove v0 topdown/graphql.go (!)

Signed-off-by: Anders Eknert <anders.eknert@apple.com>
2026-03-06 22:07:35 +00:00
Anders Eknert e03ac2f200 Bump golangci-lint, more gocritic linters (#8052)
- Bump golangci-lint -> 2.6.2
- Fix all `deprecatedComment` "notices should be in a dedicated paragraph, separated from the rest" reports
- Enable `appendCombine` and fix all "appendCombine: can combine chain of X appends into one" notices
- Enable `preferFprint` and fix the few reported issues
- Fix various issues reported only once or twice, like `zeroByteRepeat`

Signed-off-by: Anders Eknert <anders.eknert@apple.com>
2025-11-17 11:08:39 +01:00
Anders Eknert e43ef0a979 Use any in place of interface{} (#7566)
Earlier this evening I tried to run the Go
[modernize](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/modernize)
analyzer on OPA. That didn't go as planned:

- https://github.com/golang/go/issues/73661
- https://github.com/golang/go/issues/73663

While we wait for that to be fixed, I figured an old-fashioned
search-and-replace across the repo may work for at least the
`interface{}` to `any` conversion. That should help make it easier
to see the other fixes as applied by the modernize tool once it has
had those issues resolved.

Signed-off-by: Anders Eknert <anders@styra.com>
2025-05-12 13:57:48 +02:00
Johan Fylling a179a24c48 v1 API
All packages, except for `cmd` and `internal`, have been moved into a new `v1` root package.

Old packages are kept for backwards-compatibility reasons. All contained code is replaced with simple type aliases and proxy functions to `v1` implementations.

Old packages default to the Rego v0 syntax, new `v1` packages default to the Rego v1 syntax.

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-12-12 15:27:34 +01:00
Johan Fylling 7bb6dbe36b Preparing for v1 API
Moving (most) source to v1 root package to prepare for v0/v1 API separation.

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-12-12 15:09:03 +01:00
Johan Fylling 9b289b0bb6 Respect runtime rego-version in RESTful policy API (#7183)
* Respect runtime rego-version in RESTful policy API

Updating `/v1/policies` RESTful server endpoint to respect the `--v0-compatible`/`--v1-compatible` flags.

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-11-20 17:09:50 +01:00
Jessie Wu 0d50f52f45 Customize status bundle_loading_duration_ns and add tests
Signed-off-by: Jessie Wu <jwu730@bloomberg.net>
2024-11-19 09:35:17 -08:00
Stephan Renatus 20885fe4a9 golangci: bump version, addess all new findings
The previous version has been failing without any good reason for me,
so let's try this.

About the version pick: It's not the latest version (v1.62.0 at the
moment), because that would introduce a new revive rule,
redeclares-builtin-id, and that flags every variable called `min` or
`max` in the code base. I had started addressing these, but they were
just too many.

The new issues related to this version are mostly that it complains
whenever it finds a non-static string that makes its way into a printf-
like function. However, that's a common pattern in some place here, so
I've sprinkled some nolint:govet on it.

Signed-off-by: Stephan Renatus <stephan@styra.com>
2024-11-14 20:36:50 +01:00
Philip Conrad d2c0459cc4 test: Parallelize package tests in high-cost packages. (#7126)
* test: Parallelize package level tests in high-cost packages.

This commit adds `t.Parallel()` calls to the beginning of many tests
across several Go packages in OPA. The slowest packages (taking ~10s or
more) have been instrumented where possible as a proof-of-concept. On a
machine with many cores, the tests now will complete as fast as the
slowest test per package, instead of the sum of all the tests in a
particular package.

* server/server_test: Remove 3x tests from parallel set.

This commit fixes a data race that could occur in the `server` package
tests, because 3x tests were modifying package variables under
`internal/version`. These tests now run sequentially, and are not
included in the parallel test set.

* plugins/bundle/plugin_test: Remove 2x tests from the parallel set.

Two tests in this package modified a package variable directly, and as
such cannot be safely run in parallel with each other or any other tests
in the package.

* topdown/*_test: t.Parallel refactors.

This commit wraps up a large batch of fairly mechanical refactorings to
add t.Parallel() annotations to almost every test under `topdown`. The
tests that could not be safely parallelized now have explicit warning
comments on them describing why they are not safe to run in parallel.

* storage/disk: t.Parallel refactors.

This commit bundles up test parallelization changes for the
`storage/disk` package, dramatically reducing its execution time.

* topdown/net_test: Remove sub-test parallelization.

* rego: t.Parallel refactors.

This commit includes a bundle of t.Parallel refactoring changes for the
`rego` package, including a timer-related bugfix, and a slight change on
a cancellation test to reduce its overall cost during test runs (the
logic is preserved, but the mandatory timeouts are lower now).

* test: Fixes for sporadic test breakages.

---------

Signed-off-by: Philip Conrad <philip@chariot-chaser.net>
2024-11-12 12:06:09 -05:00
Johan Fylling 6af5e79bd9 storage: Optimized read mode for default data storage
A new optimized read mode has been added to the default in-memory store, where data written to the store is eagerly converted to AST values (the data format used during evaluation). This pre-converted data is faster to read, and won’t cause memory spikes during load; but comes with slower data writes (affects startup and bundle load/update time) and a larger lowest overall memory footprint for OPA. Can be enabled for `opa run`, `opa eval`, and `opa bench` by setting the `—optimize-store-for-read-speed`. See http://localhost:8888/docs/edge/policy-performance/#storage-optimization.

Implements: #4147

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
Co-authored-by: Ashutosh Narkar <anarkar4387@gmail.com>
2024-10-30 12:12:21 +01:00
Stephan Renatus 34b80b339a server/writer: use Header().Set() not Header().Add() to avoid duplicate content-type headers
Signed-off-by: Stephan Renatus <stephan@styra.com>
2024-10-15 19:45:58 +02:00
Stephan Renatus cb3ac5a838 server/writer: don't call WriteStatus() twice on encoding errors
Signed-off-by: Stephan Renatus <stephan@styra.com>
2024-10-15 19:45:58 +02:00
Ashutosh Narkar 2c56293695 Add a new inter-query value cache to cache data across queries
This commit adds a new inter-query value cache that built-in
functions can use to cache information across queries.
For example, the `regex` and `glob` builtins can use this
to cache compiled regex and glob match patterns respectively.

The number of entries in the cache can be configured via the OPA
config. By default there is no limit.

Fixes: #6908

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2024-09-23 13:03:03 -07:00
Johan Fylling 8de480e5dd rego-v1: Future-proofing server pkg tests to be 1.0 compatible (#7029)
Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-09-18 13:51:54 +02:00
Brett McBride fd0821c1b3 distributedtracing: adding distributed tracing resource attributes
Adding a resource map to the distributed_tracing
config. Entries in this map will be passed through to the OpenTelemetry SDK where they will be
added as resource attributes. The available resource attributes are service.namespace,
service.version and service.instance.id. see
https://opentelemetry.io/docs/specs/semconv/resource/

Fixes: #6492

Signed-off-by: Brett McBride <brett@deakin.edu.au>
2024-08-26 14:39:08 -07:00
Ashutosh Narkar ebc3ab241a Always include HTTP request context in incoming req context
Previously the HTTP request context was included in the
request context at the info access log level. This means
if the access log level was set to error for instance,
the context would not include the http request context and
hence it would not be surfaced via decision logs.

This change always add the http request context to the request
context so that HTTP info like headers will be surfaced via decision
logs irrespective of the access log level.

Fixes: #6951

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2024-08-23 07:50:56 -07:00
Philip Conrad ee9ab0bf75 util+server: Fix bug around chunked request handling. (#6906)
This commit fixes a request handling bug introduced in #6868, which
caused OPA to treat all incoming chunked requests as if they had
zero-length request bodies.

The fix detects cases where the request body size is unknown in the
DecodingLimits handler, and propagates a request context key down to
the `util.ReadMaybeCompressedBody` function, allowing it to correctly
select between using the original `io.ReadAll` style for chunked
requests, or the newer preallocated buffers approach (for requests of
known size).

This change has a small, but barely visible performance impact for large
requests (<5% increase in GC pauses for a 1GB request JSON blob), and
minimal, if any, effect on RPS under load.

Fixes: #6904

Signed-off-by: Philip Conrad <philip@chariot-chaser.net>
2024-08-01 15:22:51 -04:00
Aaron Campbell d48fdd99ac server: Add missing handling for explain=fails to the REST API.
Signed-off-by: Aaron Campbell <62760750+acamatcisco@users.noreply.github.com>
2024-07-23 15:36:44 -07:00
Philip Conrad c5706eef7c server+util: Limit max request sizes, prealloc request buffers (#6868)
This commit introduces a few major changes:
 - (Breaking change) Limits now exist for maximum request body sizes.
 - Buffers are preallocated for reading request bodies.
 - Buffers are preallocated for decompressing request bodies.
 - Gzip decoder instances are reused in a `sync.Pool` across requests.

The effect on garbage collection is dramatically fewer GC pauses, giving
a roughly 9% RPS improvement in load tests with gzipped request bodies.
For larger request sizes, the number of GC pauses is dramatically
reduced, although the peak pause time may increase by a few percent.

Implementation notes:
 - The DecodingLimits handler enforces the max request body size both
   through a Content-Length check, and a MaxBytesReader wrapper around
   the payload.
 - The DecodingLimits handler passes the gzip payload size limit down
   using a context key.

Signed-off-by: Philip Conrad <philipaconrad@gmail.com>
2024-07-22 13:15:08 -04:00
Philip Conrad 4e01537fe7 server/authorizer: Fix gzip payload handling. (#6825)
This PR fixes an issue where an OPA running authorization policies would
be unable to handle gzipped request bodies.

Example OPA CLI setup:

    opa run -s --authorization=basic

Example request:

    echo -n '{}' | gzip | curl -H "Content-Encoding: gzip" --data-binary @- http://127.0.0.1:8181/v1/data

This would result in unhelpful error messages, like:

```json
{
  "code": "invalid_parameter",
  "message": "invalid character '\\x1f' looking for beginning of value"
}
```

The cause was that the request body handling system in the
`server/authorizer` package did not take gzipped payloads into
account. The fix was to borrow the gzip request body handling function
from `server/server.go`, to transparently decompress the body when
needed.

Fixes: #6804

Signed-off-by: Philip Conrad <philipaconrad@gmail.com>
2024-06-27 09:55:19 +02:00
Johan Fylling 5464b005e8 Bumping golangci-lint to v1.59.1 (#6817)
Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-06-19 15:13:43 +02:00
Ashutosh Narkar a8ac7b38bb plugins/logs: Include http request context in decision logs
It would be useful if users had the ability to enhance the
decision log with info from the incoming HTTP request such as
headers. This change allows users to configure headers whose
values if present in the incoming HTTP request would be
surfaced via the decision log. This can be extended in the
future to include more context from the request.

Fixes: #6693

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2024-05-20 11:08:42 -07:00
Ashutosh Narkar a400281406 server: Keep default decision path in-sync with manager's config
This change attempts to keep the default decision path used by the server
in sync with the one defined on the manager's config. Currently the
server only updates the default decision path when it's initialized and
when there is a commit on the store. The issue happens when the default
decision path is updated via the discovered config. In this case, the
manager's config is updated but there could be no store txn. Hence
the updated value of default decision path is not taken into account by
the server.

Fixes: #6697

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2024-04-24 12:06:09 -07:00
Charlie Egan a1cefe20cd server: Retry cert reloading & test case step
In workflow runs like this:
https://github.com/open-policy-agent/opa/actions/runs/7803493290/job/21283458848#step:3:317

We can see two problems. This commit is meant to address them.

First, the test failed with this message:

```
expected unknown certificate authority error but got: Get "https://127.0.0.1:38699/v1/data": write tcp 127.0.0.1:52786->127.0.0.1:38699: write: connection reset by peer
```

Now this step in the test is retried like the other steps in the test
since it can fail too.

Second, the error `failed to reload TLS config` appears many times in
the logs for that test. This issue is caused by the server attempting to
read the new cert, key, and CA contents from disk while they are still
being written to. This PR also introduces a 100ms pause between upto 5
attempts to reload the config for any given change to the state on disk.
This should mean that the error is seen only when is is actually an
issue and the reload has failed after a reasonable time. In most cases,
running locally, the reload happens without error on the first run.

Signed-off-by: Charlie Egan <charlie@styra.com>
2024-04-04 12:38:48 -07:00
Teemu Koponen 8fde8264d7 server: Remove unnecessary AST-to-JSON conversions.
This time for v0QueryPath, v1DataGet, and v1DataPost.

Signed-off-by: Teemu Koponen <koponen@styra.com>
2024-04-03 16:33:37 -07:00
Teemu Koponen 27d6829d4c server: Remove an unnecessary AST-to-JSON conversion for the eval input.
The cost of this can become non-trivial with larger inputs.

Signed-off-by: Teemu Koponen <koponen@styra.com>
2024-04-03 12:40:40 -07:00
occupyhabit d6c8c1b51b chore: remove repetitive words
Signed-off-by: occupyhabit <wangmengjiao@outlook.com>
2024-03-25 11:28:12 -07:00
Stephan Renatus d978deb8c7 cleanup: use errors.Join
Signed-off-by: Stephan Renatus <stephan@styra.com>
2024-02-27 08:58:08 -08:00
Ashutosh Narkar 737b213ba6 Allow TLS cipher suites to be set for the OPA server
This change adds a new flag to `opa run` to allow
users to specify a list of enabled TLS 1.0–1.2 cipher
suites. This allows users to control the cipher suites
the OPA server supports during a TLS handshake.

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2024-01-23 14:20:29 -08:00
Rudrakh Panigrahi f063c90275 Clean expired cache entries periodically
Regularly clean up of cache entries that have expired for a more efficient use of memory.
Introduce two new parameters to tune clean up frequency and threshold for forced FIFO eviction.

Fixes #5320

Signed-off-by: Rudrakh Panigrahi <rudrakh97@gmail.com>
2024-01-09 13:13:30 -08:00
Charlie Egan 1609eb5ba4 server: Use tlsconfig mutex when accessing certpool
This was missed in https://github.com/open-policy-agent/opa/pull/6415

https://github.com/open-policy-agent/opa/actions/runs/7194437460/job/19595009978?pr=6476

We have a warning of this data race here:

```
==================
WARNING: DATA RACE
Write at 0x00c009b562e8 by goroutine 1815:
  github.com/open-policy-agent/opa/server.(*Server).reloadTLSConfig()
      /src/server/certs.go:65 +0x608
  github.com/open-policy-agent/opa/server.(*Server).getListener.(*Server).certLoopNotify.func2()
      /src/server/certs.go:174 +0x434
  github.com/open-policy-agent/opa/server.TestCertPoolReloading.func1()
      /src/server/server_test.go:5105 +0x4f
  github.com/open-policy-agent/opa/server.TestCertPoolReloading.func2()
      /src/server/server_test.go:5108 +0x41

Previous read at 0x00c009b562e8 by goroutine 1824:
  github.com/open-policy-agent/opa/server.(*Server).getListenerForHTTPSServer.func1()
      /src/server/server.go:649 +0x145
  crypto/tls.(*Conn).readClientHello()
      /usr/local/go/src/crypto/tls/handshake_server.go:149 +0x97d
  crypto/tls.(*Conn).serverHandshake()
      /usr/local/go/src/crypto/tls/handshake_server.go:42 +0x64
  crypto/tls.(*Conn).serverHandshake-fm()
      <autogenerated>:1 +0x47
  crypto/tls.(*Conn).handshakeContext()
      /usr/local/go/src/crypto/tls/conn.go:1552 +0x615
  crypto/tls.(*Conn).HandshakeContext()
      /usr/local/go/src/crypto/tls/conn.go:1492 +0x16b8
  net/http.(*conn).serve()
      /usr/local/go/src/net/http/server.go:1891 +0x16c0
  net/http.(*Server).Serve.func3()
      /usr/local/go/src/net/http/server.go:3086 +0x4f
```

Signed-off-by: Charlie Egan <charlie@styra.com>
2023-12-13 09:28:45 -08:00
Charlie Egan a307ec4135 server: Support fsnotify reloading of certs (#6415)
Reload certs, keys and optionally the CA cert pool when they change on
disk.

The polling behaviour and flag is also still supported.
2023-12-13 08:52:59 +00:00
Charlie Egan f102042ea8 discovery: Make status updates non blocking (#6345)
Fixes #6343

A status endpoint that times out, will no longer delay boots.

Signed-off-by: Charlie Egan <charlie@styra.com>
2023-11-06 16:19:09 -06:00
Ashutosh Narkar 9a1a42758d deps: Bump OpenTelemetry-Go Contrib 0.45.0
This version includes security fixes which addresses
vulnerability CVE-2023-45142.More details can be
found at
https://github.com/open-telemetry/opentelemetry-go-contrib/security/advisories/GHSA-rcjv-mgp8-qvmr.

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2023-10-17 12:25:48 -07:00
Ashutosh Narkar 8115976890 server: Remove partial query parameter (#6300)
The partial query parameter has been marked as deprecated since
v0.23.0. It's also removed from the docs since that time.

Fixes: #2266

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2023-10-11 10:09:24 +02:00
aarnautu 38c997eef4 This change adds support to configurable prometheus buckets
http_request_duration has fixed, hardcoded number of buckets with no possibility to tweak them
For cases when the most of the latencies are above 1ms, with only 4 available buckets there's no good insight on OPA's performance.

This implementation:
- adds the possibility for the buckets to be configurable in ```server.metrics.prom.http_request_duration_seconds.buckets``` key
- it's not a breaking change, if the buckets are not present in the configuration, the metric is configured with the existing values as a fallback

Signed-off-by: aarnautu <aarnautu@adobe.com>
2023-10-06 13:27:46 -07:00
Ashutosh Narkar 974586e0a5 server: Add test case for bundle update - query API handler scenario
This test case exercises the scenario when a bundle is being written
to the store (ie. active write transaction) and the OPA server handling
a policy eval request at the same time. The former should not block
the later.

Fixes: #4792

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2023-09-27 08:25:47 -07:00
Anders Eknert 700e2c97de Bind test server to localhost interface (#6164)
Fixes #6162

Signed-off-by: Anders Eknert <anders@styra.com>
2023-08-17 15:56:35 +02:00
Stephan Renatus abb6cf2edd server/authorizer: inline readBody (#6156)
This was a waste of space.

Signed-off-by: Stephan Renatus <stephan@styra.com>
2023-08-14 14:41:44 +02:00
Ashutosh Narkar 20612bb819 rego: Parse store modules iff modules set on the Rego object
Currently we parse store modules irrespective of whether
there are modules on the Rego object. This will result in
the compilation of those modules which triggers the bundle
activation flow. Now as part of the module compilation
we interact with the compiler's modules and run compilation
on the input modules. If let's say there are concurrent health
check requests (ie. /v1/health), this could result in a race
during the compilation process while working with the compiler's
modules.

This change avoids this situation by skipping parsing of the store
modules when none are set on the Rego object. The assumption this
change makes is that while using the rego package the compiler and
store are kept in-sync.

Fixes: #5868

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2023-07-07 01:44:53 -07:00
Stephan Renatus 511018ec95 server: extra cleanup (#6059)
This came up in the discussion of the previous cleanup PR, but I hadn't
gotten around to include it back then.

Signed-off-by: Stephan Renatus <stephan@styra.com>
2023-06-29 10:48:38 +02:00
Stephan Renatus f1b496c329 server: cleanup some handler code (#6057)
Signed-off-by: Stephan Renatus <stephan@styra.com>
2023-06-28 19:21:18 +02:00
Ashutosh Narkar 1ad567bf00 Add ability to configure Unix socket permissions
Currently if OPA listens on a Unix socket, the socket
file is created with 755 permissions. So if OPA is deployed
on k8s for example and the socket path is shared
via a volume between pods, due to the default permissions,
the socket will not be reachable for the caller. One way around
this is to match the user id for the OPA and caller containers
but that is not always possible.

This change adds a new flag to the OPA runtime that allows
to configure the permission of the socket file. In the
k8s scenario, if the file permission is updated to 777
for instance, the caller will be able to connect to OPA via
the socket.

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2023-05-02 09:07:23 -07:00
Ashutosh Narkar 208d324ab6 Include trace and span identifier in decision logs
Currently OPA's decision logs do not include the trace
and span identifier associated with a given request
handled by the server. This information if available
can be helpful to correlate logs and trace data.

This change updates the decision log format to now
include the trace and span identifier if present.

Fixes: #5230

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2023-04-05 23:25:05 -07:00
Ashutosh Narkar 9e28c5e673 Surface unauthorized response count from OPA API authz handler
Currently when OPA's HTTP server rejects requests per
the authz policy, this is not accounted for via the management APIs.
This change adds that count in the metric registry that is
part of the Status API for more visibility.

Fixes: #3378

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2023-03-27 11:19:27 -07:00
Charlie Egan b36da40ab6 [server/identifier] Support SPIFFEID use in authz (#5742)
When using OPA TLS authorization, authz policy authors will now have
access to the client certificates presented as part of the TLS
connection. This new data will be available under the key `client_certificates`.

The existing functionality where `identity` is set to the Subject RDN Sequence
is left unchanged.

When using x.509 SVIDs the SPIFFEID is presented as in the SANs of the
certificate. So this change makes that data available should users
require it. It also makes other information about the client cert
available to authz policy too.

Signed-off-by: Charlie Egan <charlie@styra.com>
2023-03-09 16:42:59 +00:00
AdrianArnautu 9e97f98d12 This change allows the HTTP clients to consume and send gzip compressed response and request body. (#5696)
It is available for the following REST API endpoints:
- GET & POST HTTP methods on /v0/data & /v1/data endpoints
- POST HTTP method on /v1/compile endpoint

HTTP clients can optionally:
- send 'Accept-Encoding: gzip' header and expect a gzip compressed body and a Content-Encoding: gzip response header. The server will send the content encoded as gzip only after a threshold defined by server.encoding.gzip.min_length (default value is 1024). If the size is below the threshold, the body is not compressed
- send 'Content-Encoding: gzip' header and a gzip compressed body and expect the server to correctly interpret the request

Fixes #5310

Signed-off-by: aarnautu <aarnautu@adobe.com>
2023-03-09 09:38:39 +01:00
Anders Eknert ab1454129f perf: stream JSON in request body (#5661)
Similar to how https://github.com/open-policy-agent/opa/pull/5596
allowed streaming JSON in the response, do the same for the request.
This has potentially bigger benefits, as the incoming request is
commonly larger than the response (admission control, terraform, etc).

Signed-off-by: Anders Eknert <anders@styra.com>
2023-02-15 14:32:03 +01:00
Stephan Renatus 4db7377969 server: pass decision_id via ctx, cleanup RemoteAddr -> RequestContext.ClientAddr (#5647)
Just s small cleanup in the server handler code. Ctx is for
request-scoped data, so let's put the decision ID there, too.

Our Eval and Log helper methods have way too many arguments already.

Signed-off-by: Stephan Renatus <stephan@styra.com>
2023-02-10 12:00:00 +01:00
Anders Eknert d001ac49d2 perf: use json.Encode to avoid extra allocation (#5596)
When sending JSON back to the client — and we do a lot of that, use
the streaming implementation of json.Encode rather than marshalling
the data into an intermediate byte array.

One curious detail here is that the streaming implementation
uses newlines to mark the end of the stream, so a few unit tests had
to be updated to expect this. Previously we would only emit a trailing
newline if "pretty" was configured.

Signed-off-by: Anders Eknert <anders@styra.com>
2023-01-26 09:49:19 +01:00