Skip to content

Latest commit

 

History

History
95 lines (66 loc) · 3.72 KB

File metadata and controls

95 lines (66 loc) · 3.72 KB

Example Fn Java FDK : Service Connector Hub - Monitoring

This example provides a Function to use as a service connector hub target. The function accepts a typed event containing a batch of source events.

Source

MetricData

Dependencies

  • [fn-events] for ConnectorHubFunction classes.
  • [fn-events-testing] for ConnectorHubFunction testing library.

Demonstrated FDK features

This example showcases how to use the fn-event ConnectorHubFunction to use a Function as the target for Monitoring source.

Step by step

Set up the connector hub with Monitoring source and Function target:

The Function entrypoint extends the ConnectorHubFunction abstract class. Note: the func.yaml entrypoint remains the class which extends ConnectorHubFunction e.g. cmd: com.fnproject.fn.examples.Function::handler

Function.java

package com.fnproject.fn.examples;

import com.fnproject.events.ConnectorHubFunction;
import com.fnproject.events.input.ConnectorHubBatch;
import com.fnproject.events.input.sch.MetricData;

public class Function extends ConnectorHubFunction<MetricData> {

    public MetricService metricService;

    public Function() {
        this.metricService = new MetricService();
    }

    @Override
    public void handler(ConnectorHubBatch<MetricData> batch) {
        for (MetricData metric : batch.getBatch()) {
            metricService.readMetric(metric);
        }
    }
}

The ConnectorHubBatch.java batch contains a list of events from Monitoring as specified in Batch Settings.

The class MetricData.java is each Monitoring Event Monitoring Schema

Function.java public class Function extends ConnectorHubFunction<MetricData> {.

To return an error response, throw RuntimeException.class. Doing so will cause the Function to return a 502 Retry policy

Test walkthrough

Unit testing ConnectorHubFunction is supported with the ConnectorHubTestFeature and FnTestingRule.

First of all, the class initializes the FnTestingRule harness, as explained in Testing Functions.

FunctionTest.java

    @Rule
    public FnTestingRule fn = FnTestingRule.createDefault();

    private final ConnectorHubTestFeature connectorHubTestFeature = ConnectorHubTestFeature.createDefault(fn);

    @Test
    public void testMetricServiceConsumesEachMetric() throws Exception {

        ConnectorHubBatch<MetricData> event = createMinimalRequest();
        connectorHubTestFeature.givenEvent(event).enqueue();

        fn.thenRun(Function.class, "handler");

        FnResult result = fn.getOnlyResult();
        assertEquals(200, result.getStatus().getCode());
    }

Use connectorHubTestFeature.givenEvent(event).enqueue(); to queue the request event and invoke the Function with fn.thenRun(Function.class, "handler");.