Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
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
50 changes: 25 additions & 25 deletions src/connections/functions/source-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,20 @@ Source functions allow you to gather data from any third-party applications with
All functions are scoped to your workspace, so members of other workspaces cannot view or use them.

> info ""
> Functions is available to all customer plan types with a free allotment of usage hours. Read more about [Functions usage limits](/docs/connections/functions/usage/), or see [your workspace's Functions usage stats](https://app.segment.com/goto-my-workspace/settings/usage?metric=functions).
> Functions is available to all customer plan types with a free allotment of usage hours. Read more about [Functions usage limits](/docs/connections/functions/usage/), or see [your workspace's Functions usage stats](https://app.segment.com/goto-my-workspace/settings/usage?metric=functions){:target="_blank"}.

![](images/source_functions_overview.png)
![A graphic illustrating Segment source functions](images/source_functions_overview.png)


## Create a source function

1. From your workspace, go to the Catalog and click the [Functions tab](https://app.segment.com/goto-my-workspace/functions/catalog).
1. From your workspace, go to the Catalog and click the [Functions tab](https://app.segment.com/goto-my-workspace/functions/catalog){:target="_blank"}.
2. Click **New Function**.
4. Select **Source Function** and click **Build**.


> success ""
> **Tip:** Want to see some example functions? Check out the templates available in the Functions UI, or in the open-source [Segment Functions Library](https://github.com/segmentio/functions-library). (Contributions welcome!)
> **Tip:** Want to see some example functions? Check out the templates available in the Functions UI, or in the open-source [Segment Functions Library](https://github.com/segmentio/functions-library){:target="_blank"}. (Contributions welcome!)

When you click **Build**, a code editor appears. Use the editor to write the code for your function, configure settings, and test the function's behavior.

Expand All @@ -34,7 +34,7 @@ When you click **Build**, a code editor appears. Use the editor to write the cod
## Code the source function

Source functions must have an `onRequest()` function defined.
This function is executed by Segment for each HTTP request sent to this function's webhook.
This function is executed by Segment for each HTTPS request sent to this function's webhook.

```js
async function onRequest(request, settings) {
Expand All @@ -44,12 +44,12 @@ async function onRequest(request, settings) {

The `onRequest()` function receives two arguments:

- `request` - an object describing the incoming HTTP request.
- `request` - an object describing the incoming HTTPS request.
- `settings` - set of [settings](#create-️settings-and-secrets) for this function.

We'll learn more about settings later, let's dive into how we can process the incoming request first.
### Request processing

To parse the JSON body of the request, use `request.json()` method as in the example below.
To parse the JSON body of the request, use the `request.json()` method, as in the following example:

```js
async function onRequest(request) {
Expand All @@ -59,7 +59,7 @@ async function onRequest(request) {
```

Use the `request.headers` object to get values of request headers.
Since it's an instance of [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers), the API is the same in both the browser and in Node.js.
Since it's an instance of [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers){:target="_blank"}, the API is the same in both the browser and in Node.js.

```js
async function onRequest(request) {
Expand All @@ -68,7 +68,7 @@ async function onRequest(request) {
}
```

To access the URL details, refer to `request.url` object, which is an instance of [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL).
To access the URL details, refer to `request.url` object, which is an instance of [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL){:target="_blank"}.

```js
async function onRequest(request) {
Expand Down Expand Up @@ -117,7 +117,7 @@ async function onRequest(request) {

##### Identify

Use [Identify calls](/docs/connections/spec/identify/) to connect user with their actions, and to record traits about them.
Use [Identify calls](/docs/connections/spec/identify/) to connect users with their actions, and to record traits about them.


```js
Expand Down Expand Up @@ -160,7 +160,7 @@ The `Segment.track()` method accepts an object with the following fields:

##### Group

[Group calls](/docs/connections/spec/group/) associate user with a group - be it a company, organization, account, project, team or other.
[Group calls](/docs/connections/spec/group/) associate users with a group, like a company, organization, account, project, or team.


```js
Expand Down Expand Up @@ -269,13 +269,13 @@ The `Segment.set()` method accepts an object with the following fields:

{% include content/functions/settings.md %}

Next, fill out this setting's value in **Test** tab, so that we can run our function and verify correct setting value is being passed.
Next, fill out this setting's value in **Test** tab, so that you can run the function and check the setting values being passed.

Note, this value is only for testing your function.

![Test Value For Setting](images/setting-in-test-tab.png){:width="500"}

Now that we have our setting set up and test value filled in, we can add code to read its value and run our function:
Now that you've configured a setting and filled in a test value, you can add code to read its value and run the function:

```js
async function onRequest(request, settings) {
Expand All @@ -290,21 +290,21 @@ When you deploy a source function in your workspace, you are prompted to fill ou

## Test the source function

You can test your code directly from the editor in two ways: either by receiving real HTTP requests through a webhook, or by manually constructing an HTTP request from within the editor.
You can test your code directly from the editor in two ways: either by receiving real HTTPS requests through a webhook, or by manually constructing an HTTPS request from within the editor.

The advantage of testing your source function with webhooks is that all incoming data is real, so you can test behavior while closely mimicking the production conditions.

### Testing source functions with a webhook

You can use webhooks to test the source function either by sending requests manually (using any HTTP client such as cURL or Insomnia), or by pasting the webhook into an external server that supports webhooks (such as Slack).
You can use webhooks to test the source function either by sending requests manually (using any HTTP client such as cURL or Insomnia) or by pasting the webhook into an external server that supports webhooks (such as Slack).

From the source function editor, copy the webhook URL from the "Auto-fill via Webhook" dialog. To trigger the source function, send the request using the `POST` method, with the `Content-Type` header set to `application/json` or `application/x-www-form-urlencoded`.

### Testing source functions manually

You can also manually construct headers and body of an HTTP request right inside the editor and test with this data, without using webhooks.
You can also manually construct the headers and body of an HTTPS request right inside the editor and test with this data without using webhooks.

![Test HTTP Request](images/test-manual.png){:width="500"}
![Test HTTPS Request](images/test-manual.png){:width="500"}

## Save and deploy the function

Expand All @@ -318,13 +318,13 @@ You can also choose to **Save & Deploy** to save the changes, and then choose wh

## Source functions logs and errors

Your function might encounter errors that you missed during testing, or you might intentionally throw errors in your code (for example if the incoming request is missing required fields).
Your function might encounter errors that you missed during testing, or you might intentionally throw errors in your code (for example, if the incoming request is missing required fields).

If your function throws an error, execution halts immediately. Segment captures the incoming request, any console logs the function printed, and the error, and displays the this information in the function's **Errors** tab. You can use this tab to find and fix unexpected errors.
If your function throws an error, execution halts immediately. Segment captures the incoming request, any console logs the function printed, and the error, and displays this information in the function's **Errors** tab. You can use this tab to find and fix unexpected errors.

![Source Function Error Logs](images/error-logs-source.png)

Functions can throw [an Error or custom Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error), and you can also add additional helpful context in logs using the [`console` API](https://developer.mozilla.org/en-US/docs/Web/API/console).
Functions can throw [an Error or custom Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error){:target="_blank"}, and you can also add additional helpful context in logs using the [`console` API](https://developer.mozilla.org/en-US/docs/Web/API/console){:target="_blank"}.
For example:

```js
Expand All @@ -348,7 +348,7 @@ async function onRequest(request, settings) {
### Error types

- **Bad Request** is any error thrown by your code not covered by the other errors.
- **Invalid Settings**: A configuration error prevented Segment from executing your code. If this error persists for more than an hour, [contact Segment Support](https://segment.com/help/contact/).
- **Invalid Settings**: A configuration error prevented Segment from executing your code. If this error persists for more than an hour, [contact Segment Support](https://segment.com/help/contact/){:target="_blank"}.
- **Message Rejected**: Your code threw `InvalidEventPayload` or `ValidationError` due to invalid input.
- **Unsupported Event Type**: Your code does not implement a specific event type (`onTrack()`, etc.) or threw a `EventNotSupported` error.
- **Retry** - Your code threw `RetryError` indicating that the function should be retried.
Expand All @@ -365,14 +365,14 @@ Segment only attempts to run your source function again if a **Retry** error occ

### Editing and deleting source functions

If you are a **Workspace Owner** or **Functions Admin**, you can manage your source function from the [Functions](https://app.segment.com/goto-my-workspace/functions/catalog) tab in the catalog.
If you are a **Workspace Owner** or **Functions Admin**, you can manage your source function from the [Functions](https://app.segment.com/goto-my-workspace/functions/catalog){:target="_blank"} tab in the catalog.

### Connecting source functions

> note ""
> You must be a **Workspace Owner** or **Source Admin** to connect an instance of your function in your workspace.

From the [Functions tab](https://app.segment.com/goto-my-workspace/functions/catalog), click **Connect Source** and follow the prompts to set it up in your workspace.
From the [Functions tab](https://app.segment.com/goto-my-workspace/functions/catalog){:target="_blank"}, click **Connect Source** and follow the prompts to set it up in your workspace.

Once configured, find the webhook URL - either on the **Overview** or **Settings → Endpoint** page.

Expand All @@ -390,4 +390,4 @@ The maximum payload size for an incoming webhook payload is 512 KiB.

##### What is the timeout for a function to execute?

The execution time limit is 5 seconds, however Segment strongly recommends that you keep execution time as low as possible. If you are making multiple external requests you can use async / await to make them concurrently, which will help keep your execution time low.
The execution time limit is five seconds, however Segment strongly recommends that you keep execution time as low as possible. If you are making multiple external requests you can use async / await to make them concurrently, which will help keep your execution time low.