Skip to content

Calling Remote Functions

Chris O'Hara edited this page Jul 2, 2024 · 1 revision

The previous calling functions guide showed how to call a function from the Dispatch endpoint that's hosting it.

It's also possible to call functions hosted by other Dispatch endpoints.

Building a call

To build a call to a Dispatch function, three things are needed:

  1. the URL of the Dispatch endpoint that the function resides on
  2. the name of the function
  3. input to the function

First, prepare input for the function using the dispatchproto.Marshal function:

argument := 23

input, err := dispatchproto.Marshal(argument)
if err != nil {
    // handle error
}

The input must be serializable (refer to the guide for defining functions for more information).

Next, prepare a function call:

endpointURL := "http://example.com"
functionName := "myFunction"

call, err := dispatchproto.NewCall(endpointURL, functionName, input)
if err != nil {
    // handle error
}

Finally, dispatch the call using one of the methods below.

Dispatching a call

Getting a client for the Dispatch API

Using a Dispatch endpoint

If a Dispatch endpoint is available, access a client for the Dispatch API using:

client, err := endpoint.Client()
if err != nil {
    // handle error
}

If an error occurs accessing the client, it means the Dispatch endpoint was not automatically able to configure a client. See the section below if this occurs.

To dispatch a function call using a client:

Manual construction

A client for the Dispatch API can be constructed manually.

client, err := dispatchclient.New()
if err != nil {
    // handle error
}

By default, the client will attempt to parse the Dispatch API key from the DISPATCH_API_KEY environment variable. Note that the Dispatch CLI sets this automatically after you run dispatch login.

It's also possible to pass the API key manually, using:

client, err := dispatchclient.New(dispatchclient.APIKey(yourAPIKey))

Dispatching a call using a client

id, err := client.Dispatch(context.TODO(), call)
if err != nil {
    // handle error
}

Just like in the previous calling guide, the return value is a globally unique identifier for the dispatched function call. As a reminder, the function is executed asynchronously.

Dispatching a batch of calls

The client can also dispatch a batch of function calls atomically:

batch := client.Batch()

batch.Add(call1)
batch.Add(call2)

ids, err := batch.Dispatch(context.TODO())