This method returns a context of type AudienceFeedConnectorBaseInstanceContext or an extended context of type InstanceContext.
We recommend you to use the extended context in order to simplify the reuse of objects and variables in the plugin code.
The original context format contains the feed metadata and its properties.
ctx (AudienceFeedConnectorBaseInstanceContext)
The original format of the AudienceFeedConnectorBaseInstanceContext type is
Parameter
Type
Description
feed
AudienceSegmentExternalFeedResource
Represents the external feed resource for the audience segment.
feedProperties
PropertiesWrapper
Wrapper for properties associated with the feed, containing metadata and configurations.
With the object feed (AudienceSegmentExternalFeedResource) that represents the external feed resource for the audience segment:
Parameter
Type
Description
id
string
Unique identifier for the audience segment external feed.
plugin_id
string
Identifier for the plugin associated with the feed.
organisation_id
string
Identifier for the organization that owns the feed.
group_id
string
Identifier for the group to which the feed belongs.
artifact_id
string
Identifier for the specific plugin artifact related to the feed.
version_id
string
Version identifier for the feed, indicating its versioning.
selected_identifying_resources
IdentifyingResourceShape
optional
Optional array of identifying resources used for segment identification.
created_by
string
Optional identifier for the user that created the feed.
The extended context contains the feed metadata, the feed properties, plus a bunch of useful variables and objects.
request (ExternalSegmentCreationRequest, required): An object containing the details necessary for creating the segment. It is sent by the platform at the feed creation.
request object format:
Parameter
Type
Description
feed_id
string
The unique identifier of the feed
segment_id
string
The unique identifier of the segment related to the feed
datamart_id
string
The identifier for the datamart of the segment
context (InstanceContext, required): The context in which the feed creation is executed, containing various configuration and resource objects.
Check the instance context section to understand the format of the feed instance context.
You can find the extended context interface in the returns tab.
Return
Resolves to an object containing the status of the segment creation process, along with an optional message and visibility.
// Trigger by the creation of a feed instance
protected async onExternalSegmentCreation(
_: ExternalSegmentCreationRequest,
ctx: InstanceContext,
): Promise<ExternalSegmentCreationPluginResponse> {
this.logger.debug(`${ctx.loggerPrefix} - onExternalSegmentCreation step`);
try {
if ( !hasIdentifyingResource(ctx) ) {
throw new Error(
`Your User Profiles do not contain enough information for Linkedin connector to rely on them alone. Either an ID (mobile id or hashed email) OR the couple first and last name are required. Please contact your account manager.`,
);
}
if (ctx.feedProperties.partnerSegmentId) {
return await knownPartnerSegmentIdWorkflow({
partnerSegmentId: ctx.feedProperties.partnerSegmentId,
ctx,
logger: this.logger,
});
}
return unknownPartnerSegmentIdWorkflow({ ctx, logger: this.logger });
} catch (err) {
this.logger.error(`${ctx.loggerPrefix} - onExternalSegmentCreation - something went wrong:`, err);
return {
status: 'error',
message: (err as Error).message,
visibility: 'PUBLIC',
};
}
}
onExternalSegmentConnection
Establishing connection with segment on destination platform.
This method check the availability of the segment on the destination platform.
Also, through the instance context method, this onExternalSegmentConnection method may validate feed properties and selected identifying resources. It is not mandatory at this step as it was supposed to be done beforehand.
request (ExternalSegmentConnectionRequest, required): An object containing the details necessary for creating the segment. It is sent by the platform at the feed creation.
request object format:
Variable
Type
Description
feed_id
string
The unique identifier of the feed
segment_id
string
The unique identifier of the segment related to the feed
datamart_id
string
The identifier for the datamart of the segment
context (InstanceContext, required): The context in which the feed creation is executed, containing various configuration and resource objects.
Check the instance context section to understand the format of the feed instance context.
You can find the extended context interface in the returns tab.
Return
Resolves to an object containing the status of the segment creation process, along with an optional message and visibility.
protected async onExternalSegmentConnection(
_: ExternalSegmentConnectionRequest,
ctx: InstanceContext,
): Promise<ExternalSegmentConnectionPluginResponse> {
this.logger.debug(`${ctx.loggerPrefix} - onExternalSegmentConnection step.`);
try {
if (!ctx.properties.partnerSegmentId) {
throw new Error(`partnerSegmentId property is undefined while it should be by now`);
}
const partnerSegmentInfos = await ctx.partnerApiClient.fetchDMPSegment(ctx.properties.partnerSegmentId);
this.logger.debug(
`${ctx.loggerPrefix} - onExternalSegmentCreation - The partner segment Id (${ctx.properties.partnerSegmentId}) was retrieved: `,
linkedinSegmentInfos,
);
return Promise.resolve({ status: 'ok' });
} catch (err) {
if ((err as CustomError).statusCode === 404) {
return {
status: 'external_segment_not_ready_yet',
message: 'partner segment is not ready yet',
};
}
this.logger.error(`${ctx.loggerPrefix} - onExternalSegmentConnection: something went wrong: `, err);
return {
status: 'error',
message: (err as Error).message,
};
}
}
onUserSegmentUpdate
This method sends the user identifiers (insertion or deletion) or prepares the payload to be sent to the partner platform.
Depending on the plugin output type, this method will have different roles and return different objects.
Single API calls (classic plugin)
This method sends the user identifiers (insertion or deletion) to the partner platform.
Batch API calls
This method inserts the user identifiers in the batch through the returned object - it can be for both insertion or deletion.
The batch will be sent to the partner platform through the onBatchUpdate method.
File delivery
This method inserts the user identifiers in the file through the returned object - it can be for both insertion or deletion.
Also, through the instance context method, this onUserSegmentUpdate method may again validate feed properties and selected identifying resources. It is not mandatory at this step again as it was supposed to be done beforehand.
request (UserSegmentUpdateRequest, required): An object containing the details necessary for creating the segment. It is sent by the platform at the feed creation.
request object format:
Parameter
Type
Description
feed_id
string
unique identifier for the feed associated with the user segment update
session_id
string
identifier for the session during which the update is being made
datamart_id
string
identifier for the datamart where the user segment resides
segment_id
string
unique identifier for the segment being updated
user_identifiers
UserIdentifierInfo[]
array of user identifiers from the segment to send to the partner platform
user_profiles
UserProfileInfo[]
array of user profiles from the segment to send to the partner platform
ts
number
timestamp indicating when the update request was created
operation
UpdateType
type of update operation being performed, indicating whether it is an add, remove, or modify operation
context (InstanceContext, required): The context in which the feed creation is executed, containing various configuration and resource objects.
Check the instance context section to understand the format of the feed instance context.
You can find the extended context interface in the returns tab.
Return (batch case)
Resolves to an object containing the batch of users identifiers to update on the segment destination platform.
request (TroubleshootActionFetchDestinationAudience, required): An object containing the details necessary for handling the troubleshoot.
Parameter
Type
Description
feed_id
string
The unique identifier of the feed
segment_id
string
The unique identifier of the segment related to the feed
datamart_id
string
The identifier for the datamart of the segment
action
enum['FETCH_DESTINATION_AUDIENCE']
context (InstanceContext, required): The context in which the feed creation is executed, containing various configuration and resource objects.
Check the instance context section to understand the format of the feed instance context.
You can find the extended context interface in the returns tab.
Return
Resolves to an object containing the status of the segment creation process, along with an optional message and visibility.
Data to be displayed in the troubleshooting section of the feed card. It must provide as much data as possible to compare identifiers received, stored and used by the partner platform
Code
Code example
protected async onTroubleshoot(
request: TroubleshootActionFetchDestinationAudience,
ctx: InstanceContext,
): Promise<ExternalSegmentTroubleshootResponse> {
if (request.action === 'FETCH_DESTINATION_AUDIENCE') {
if (!ctx.properties.partnerSegmentId) {
throw new Error(`partnerSegmentId property is undefined while it should be by now`);
}
const partnerSegmentInfos = await ctx.partnerClient.fetchDMPSegment(ctx.properties.partnerSegmentId);
const troubleshootData = {
matchedRate: this.computeMatchRate(partnerSegmentInfos),
audienceInfos: partnerSegmentInfos,
};
return {
status: 'ok',
message: 'Here is the destination audience!',
data: troubleshootData,
};
}
return { status: 'not_implemented' };
}
Batching
This method is required if we batch the calls to the partner API or to send a flat file.
onBatchUpdate
Send the batched payload of user identifiers to the partner platform.
This payload is prepared by our platform thanks to the unitary calls to the onUserSegmentUpdate method.
Array of items (insertion/deletion) to be sent to the partner platform
ts
number
Timestamp indicating when the batch update request was created
context
AudienceFeedBatchContext
Context information relevant to the batch update process
We do not use this variable from this parameter.
context (InstanceContext, required): The context in which the feed creation is executed, containing various configuration and resource objects.
Check the instance context section to understand the format of the feed instance context.
You can find the extended context interface in the returns tab.
Return
Resolves to an object containing the status of the users identifiers sent to the destination platform, along with an optional message.
Promise<BatchUpdatePluginResponse>
BatchUpdatePluginResponse object format:
Parameter
Type
status
enum['OK' | 'ERROR' | 'RETRY']
message
string, optional
next_msg_delay_in_ms
number, optional
sent_items_in_success
number
sent_items_in_error
number
Code
Code example
protected async onBatchUpdate(
request: BatchUpdateRequest<AudienceFeedBatchContext, Payload>,
ctx: InstanceContext,
): Promise<BatchUpdatePluginResponse> {
this.logger.debug(`${ctx.loggerPrefix} - onBatchUpdate - starting.`);
try {
if (!ctx.properties.partnerSegmentId) {
throw new Error(`partnerSegmentId property is undefined while it should be by now`);
}
if (!request.batch_content.length) {
this.logger.debug(`${ctx.loggerPrefix} - onBatchUpdate - Empty batch content. Returning`);
return {
status: 'OK',
sent_items_in_success: 0,
sent_items_in_error: 0,
};
}
// SendPayloads is a function that sends the batched users to the partner platform.
const updateStats = await ctx.partnerClient.SendPayload({
partnerSegmentId: ctx.properties.partnerSegmentId,
payload: request.batch_content,
});
this.logger.debug(
`${ctx.loggerPrefix} - onBatchUpdate - total sent users: ${updateStats.total} / success: ${updateStats.successful} / errors: ${updateStats.errors} / errors details: `,
{ errorDetails: updateStats.messages },
);
return Promise.resolve({
status: 'OK',
sent_items_in_success: updateStats.successful,
sent_items_in_error: updateStats.errors,
});
} catch (err) {
this.logger.error(`${ctx.loggerPrefix} - onBatchUpdate - something went wrong:`, err);
return {
status: 'ERROR',
message: (err as Error).message,
sent_items_in_success: 0,
sent_items_in_error: request.batch_content.length,
};
}
}
Authentication
onAuthenticationStatusQuery
Check the authentication status of the connector. If the connector has no valid authentication, it must respond with a url to let the user authenticate through the desired method.
request (ExternalSegmentAuthenticationRequest): Request forwarded from the partner response after authentication on their
Parameter
Type
Description
user_id
string
unique identifier for the user making the authentication request
plugin_version_id
string
identifier for the version of the plugin being used for authentication
params
object, optional
[key: string]
Optional object containing additional parameters received in the redirection from the partner authentication. Concerning the Oauth2.0 protocol, the code is present within this array
Return
Resolves to an object containing the response status along the optional message.
Promise<ExternalSegmentAuthenticationResponse>
Parameter
Type
Description
status
enum['ok' | 'error' | 'not_implemented']
Status of the authentication process indicating success or failure
message
string, optional
optional message providing additional information about the authentication status
Code
Code example
protected async onAuthentication(
request: ExternalSegmentAuthenticationRequest,
): Promise<ExternalSegmentAuthenticationResponse> {
this.logger.info(
`onAuthentication - Response received from partner. Converting User ${request.user_id}'s code into a refresh token and storing it.`,
);
try {
if (!request.params || !Object.keys(request.params).length) {
throw new Error('No params found in request.');
}
const encryption_key = await this.retrieveEncryptionKey()
const expectedKeys = ['code', 'state'];
const missingKeys = expectedKeys.filter((key) => !request.params?.[key]);
if (missingKeys.length) {
throw new Error(`Missing keys in request.params: ${missingKeys.join(', ')}`);
}
const encryptedState = request.params['state'];
const decryptedState = this.decryptString(encryptedState, encryption_key);
const state = this.parseAndValidateState(decryptedState);
this.logger.info(`onAuthentication - state decrypted and parsed:`, state);
const code = request.params['code'];
const refresh_token = await retrieveRefresehToken(code);
await storeRefreshToken(refresh_token);
this.logger.info(
`onAuthentication - Refresh token received and stored for user ${request.user_id}.`,
);
return {
status: 'ok',
};
} catch (err) {
const requestError = (err as RequestError).response?.body || 'Unknown error';
this.logger.error(`onAuthentication - something went wrong:`, {
error: requestError
? typeof requestError === 'string'
? requestError
: JSON.stringify(requestError)
: JSON.stringify(err as Error),
});
return {
status: 'error',
message: (err as Error).message,
};
}
}
onLogout
Handle the connector logout for either a user, or a datamart.
Enable the feed creation form to dynamically suggest values from the partner solution, allowing users to select from these options. Additionally, one dynamic property may depend on another.