Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/main/java/io/roastedroot/proxywasm/impl/Imports.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import io.roastedroot.proxywasm.v1.Handler;
import io.roastedroot.proxywasm.v1.LogLevel;
import io.roastedroot.proxywasm.v1.MapType;
import io.roastedroot.proxywasm.v1.MetricType;
import io.roastedroot.proxywasm.v1.StreamType;
import io.roastedroot.proxywasm.v1.WasmException;
import io.roastedroot.proxywasm.v1.WasmResult;
Expand Down Expand Up @@ -889,4 +890,50 @@ int proxyCallForeignFunction(
return e.result().getValue();
}
}

@WasmExport
int proxyDefineMetric(int metricType, int nameDataPtr, int nameSize, int returnMetricId) {
try {
MetricType type = MetricType.fromInt(metricType);
if (type == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}

var name = string(readMemory(nameDataPtr, nameSize));
int metricId = handler.defineMetric(type, name);
putUint32(returnMetricId, metricId);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}

@WasmExport
int proxyRecordMetric(int metricId, long value) {
WasmResult result = handler.recordMetric(metricId, value);
return result.getValue();
}

@WasmExport
int proxyRemoveMetric(int metricId) {
WasmResult result = handler.removeMetric(metricId);
return result.getValue();
}

@WasmExport
int proxyIncrementMetric(int metricId, long value) {
WasmResult result = handler.incrementMetric(metricId, value);
return result.getValue();
}

@WasmExport
int proxyGetMetric(int metricId, int returnValuePtr) {
try {
var result = handler.getMetric(metricId);
putUint32(returnValuePtr, (int) result);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
}
25 changes: 25 additions & 0 deletions src/main/java/io/roastedroot/proxywasm/v1/ChainedHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -281,4 +281,29 @@ public int dispatchHttpCall(
public byte[] callForeignFunction(String name, byte[] bytes) throws WasmException {
return next().callForeignFunction(name, bytes);
}

@Override
public int defineMetric(MetricType metricType, String name) throws WasmException {
return next().defineMetric(metricType, name);
}

@Override
public WasmResult removeMetric(int metricId) {
return next().removeMetric(metricId);
}

@Override
public WasmResult recordMetric(int metricId, long value) {
return next().recordMetric(metricId, value);
}

@Override
public WasmResult incrementMetric(int metricId, long value) {
return next().incrementMetric(metricId, value);
}

@Override
public long getMetric(int metricId) throws WasmException {
return next().getMetric(metricId);
}
}
20 changes: 20 additions & 0 deletions src/main/java/io/roastedroot/proxywasm/v1/Handler.java
Original file line number Diff line number Diff line change
Expand Up @@ -410,4 +410,24 @@ default int dispatchHttpCall(
default byte[] callForeignFunction(String name, byte[] bytes) throws WasmException {
throw new WasmException(WasmResult.NOT_FOUND);
}

default int defineMetric(MetricType metricType, String name) throws WasmException {
throw new WasmException(WasmResult.UNIMPLEMENTED);
}

default WasmResult removeMetric(int metricId) {
return WasmResult.UNIMPLEMENTED;
}

default WasmResult recordMetric(int metricId, long value) {
return WasmResult.UNIMPLEMENTED;
}

default WasmResult incrementMetric(int metricId, long value) {
return WasmResult.UNIMPLEMENTED;
}

default long getMetric(int metricId) throws WasmException {
throw new WasmException(WasmResult.UNIMPLEMENTED);
}
}
45 changes: 45 additions & 0 deletions src/main/java/io/roastedroot/proxywasm/v1/MetricType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package io.roastedroot.proxywasm.v1;

/**
* Represents the type of metric in proxy WASM.
*/
public enum MetricType {
COUNTER(0),
GAUGE(1),
HISTOGRAM(2);

private final int value;

/**
* Constructor for MetricType enum.
*
* @param value The integer value of the metric type
*/
MetricType(int value) {
this.value = value;
}

/**
* Get the integer value of this metric type.
*
* @return The integer value
*/
public int getValue() {
return value;
}

/**
* Convert an integer value to a MetricType.
*
* @param value The integer value to convert
* @return The corresponding MetricType or null if the value doesn't match any MetricType
*/
public static MetricType fromInt(int value) {
for (MetricType type : values()) {
if (type.value == value) {
return type;
}
}
return null;
}
}
5 changes: 5 additions & 0 deletions src/test/go-examples/metrics/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## Attribution

This example originally came from:
https://github.com/proxy-wasm/proxy-wasm-go-sdk/blob/ab4161dcf9246a828008b539a82a1556cf0f2e24/examples/metrics
```
5 changes: 5 additions & 0 deletions src/test/go-examples/metrics/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module github.com/proxy-wasm/proxy-wasm-go-sdk/examples/metrics

go 1.24

require github.com/proxy-wasm/proxy-wasm-go-sdk v0.0.0-20250212164326-ab4161dcf924
10 changes: 10 additions & 0 deletions src/test/go-examples/metrics/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/proxy-wasm/proxy-wasm-go-sdk v0.0.0-20250212164326-ab4161dcf924 h1:wTcK6gcyTKJMeDka69AMjZYvisdI8CBXzTEfZ+2pOxI=
github.com/proxy-wasm/proxy-wasm-go-sdk v0.0.0-20250212164326-ab4161dcf924/go.mod h1:9mBRvh8I6Td6sg3CwEY+zGFE4DKaIoieCaca1kQnDBE=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
85 changes: 85 additions & 0 deletions src/test/go-examples/metrics/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Copyright 2020-2024 Tetrate
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
"fmt"

"github.com/proxy-wasm/proxy-wasm-go-sdk/proxywasm"
"github.com/proxy-wasm/proxy-wasm-go-sdk/proxywasm/types"
)

func main() {}
func init() {
proxywasm.SetVMContext(&vmContext{})
}

// vmContext implements types.VMContext.
type vmContext struct {
// Embed the default VM context here,
// so that we don't need to reimplement all the methods.
types.DefaultVMContext
}

// NewPluginContext implements types.VMContext.
func (*vmContext) NewPluginContext(contextID uint32) types.PluginContext {
return &metricPluginContext{}
}

// metricPluginContext implements types.PluginContext.
type metricPluginContext struct {
// Embed the default plugin context here,
// so that we don't need to reimplement all the methods.
types.DefaultPluginContext
}

// NewHttpContext implements types.PluginContext.
func (ctx *metricPluginContext) NewHttpContext(contextID uint32) types.HttpContext {
return &metricHttpContext{}
}

// metricHttpContext implements types.HttpContext.
type metricHttpContext struct {
// Embed the default http context here,
// so that we don't need to reimplement all the methods.
types.DefaultHttpContext
}

const (
customHeaderKey = "my-custom-header"
customHeaderValueTagKey = "value"
)

// counters is a map from custom header value to a counter metric.
// Note that Proxy-Wasm plugins are single threaded, so no need to use a lock.
var counters = map[string]proxywasm.MetricCounter{}

// OnHttpRequestHeaders implements types.HttpContext.
func (ctx *metricHttpContext) OnHttpRequestHeaders(numHeaders int, endOfStream bool) types.Action {
customHeaderValue, err := proxywasm.GetHttpRequestHeader(customHeaderKey)
if err == nil {
counter, ok := counters[customHeaderValue]
if !ok {
// This metric is processed as: custom_header_value_counts{value="foo",reporter="wasmgosdk"} n.
// The extraction rule is defined in envoy.yaml as a bootstrap configuration.
// See https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/metrics/v3/stats.proto#config-metrics-v3-statsconfig.
fqn := fmt.Sprintf("custom_header_value_counts_%s=%s_reporter=wasmgosdk", customHeaderValueTagKey, customHeaderValue)
counter = proxywasm.DefineCounterMetric(fqn)
counters[customHeaderValue] = counter
}
counter.Increment(1)
}
return types.ActionContinue
}
Binary file added src/test/go-examples/metrics/main.wasm
Binary file not shown.
49 changes: 49 additions & 0 deletions src/test/java/io/roastedroot/proxywasm/MetricsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package io.roastedroot.proxywasm;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import com.dylibso.chicory.wasm.Parser;
import io.roastedroot.proxywasm.v1.Action;
import io.roastedroot.proxywasm.v1.MetricType;
import io.roastedroot.proxywasm.v1.ProxyWasm;
import io.roastedroot.proxywasm.v1.StartException;
import java.nio.file.Path;
import java.util.Map;
import org.junit.jupiter.api.Test;

/**
* Java port of https://github.com/proxy-wasm/proxy-wasm-go-sdk/blob/ab4161dcf9246a828008b539a82a1556cf0f2e24/examples/metrics/main_test.go
*/
public class MetricsTest {

@Test
public void testMetric() throws StartException {
var handler = new MockHandler();
var module = Parser.parse(Path.of("./src/test/go-examples/metrics/main.wasm"));
ProxyWasm.Builder builder = ProxyWasm.builder().withPluginHandler(handler);

try (var host = builder.build(module)) {
try (var context = host.createHttpContext(handler)) {
// Create headers with custom header
Map<String, String> headers = Map.of("my-custom-header", "foo");

// Call OnRequestHeaders multiple times
long expectedCount = 3;
for (int i = 0; i < expectedCount; i++) {
handler.setHttpRequestHeaders(headers);
Action action = context.callOnRequestHeaders(false);
assertEquals(Action.CONTINUE, action);
}

// Check metrics
var metric =
handler.getMetric(
"custom_header_value_counts_value=foo_reporter=wasmgosdk");
assertNotNull(metric);
assertEquals(MetricType.COUNTER, metric.type);
assertEquals(expectedCount, metric.value);
}
}
}
}
Loading