Native hooks
Some operations cannot be described declaratively: a client-side computation the API requires, a protocol that is not request and response, a response format that needs real parsing. For those, an operation names a native hook written in Rust, and the rest of the connector stays YAML.
Use a hook for the one operation that needs it. Authentication, retries, rate limits, egress policy, redaction and credential refresh still come from the connector’s YAML, because the hook makes its requests through the connector’s HTTP client.
Declaring a hook
resources:
task:
operations:
import_csv:
display_name: Import tasks from a CSV file
description: Creates one task per CSV row, in batches of up to 500.
side_effect: true
per_item: true
params:
- { name: project, type: resource_locator, lookup: projects, required: true }
- { name: binary_property, type: binary_property, default: data }
native: import_csv
native: replaces request: and steps:. Parameters, credentials and the node’s UI are still
defined in YAML.
Hook names resolve in this order:
<connector id>::<name>(hereacme_tasks::import_csv), a hook for this connector only,<name>, a shared hook usable by several connectors.
A name that contains :: is used as is. tappet connector lint reports hooks that are not
registered.
Writing the hook
A hook implements tappet_connect::native::NativeHook:
use std::sync::Arc;
use async_trait::async_trait;
use tappet_connect::{
http::{PreparedRequest, SendOpts},
native::{register_hook, NativeCall, NativeHook},
};
use tappet_core::{Item, Json, NodeError};
/// Creates tasks from the rows of a CSV file, 500 rows per request.
struct ImportCsv;
#[async_trait]
impl NativeHook for ImportCsv {
async fn call(&self, call: NativeCall<'_, '_>) -> Result<Vec<Item>, NodeError> {
let project = call
.params
.get("project")
.and_then(Json::as_str)
.ok_or_else(|| NodeError::config("parameter 'project' is required"))?;
let property = call
.params
.get("binary_property")
.and_then(Json::as_str)
.unwrap_or("data");
let rows = read_csv_rows(call.client, call.item, property).await?;
let mut created = Vec::new();
for batch in rows.chunks(500) {
let url = api_url(call.client, &format!("/projects/{project}/tasks/batch"))?;
let mut req = PreparedRequest::new(reqwest::Method::POST, url);
req.set_body_field("tasks", Json::Array(batch.to_vec()));
let resp = call
.client
.send(&req, &SendOpts { side_effect: true, ..Default::default() })
.await?;
if let Some(tasks) = resp.body.get("tasks").and_then(Json::as_array) {
created.extend(tasks.iter().cloned().map(Item::from_value));
}
}
Ok(created)
}
}
pub fn register() {
register_hook("acme_tasks::import_csv", Arc::new(ImportCsv));
}
read_csv_rows (stream the binary property from the blob store and parse it) and api_url
(join a path to the connector’s base_url) are helpers of the hook’s own module, left out for
brevity. The rustdoc of tappet_connect::native and tappet_connect::http is the authoritative
API reference.
NativeCall gives the hook:
| Field | Contents |
|---|---|
operation | resource.operation being run |
params | Resolved parameters for this item |
client | The connector’s HTTP client: auth, retries, rate limits, egress policy, refresh-on-401 |
item, items, item_index | The current input item, all input items, and the index |
credential() | The resolved credential, if the hook needs a field directly |
Rules for hooks:
- Make every outbound request through
call.client. Opening sockets or building a separate HTTP client bypasses the egress policy and redaction, and will not pass review. - Return errors as
NodeErrorwith the right kind (configfor bad parameters,remotewith status for vendor errors). Never include secret values in messages. - Do not
unwrap()on anything derived from parameters or responses. - Read binary data through the blob store APIs; do not assume files fit in memory.
- Paired items are filled in by the runtime when the returned items have none: every output item
is paired with the current input item (or with all inputs when
per_item: false).
Custom signers
For custom_native authentication, implement tappet_connect::native::NativeSigner. A signer
receives the auth definition, the resolved credential and the outgoing request (method, URL,
headers, body bytes or form fields) and adds whatever headers or query parameters the scheme
requires:
use async_trait::async_trait;
use tappet_connect::{
auth::{set_header, SignRequest},
model::AuthDef,
native::{register_signer, NativeSigner},
};
use tappet_core::{credentials::ResolvedCredential, NodeError};
struct AcmeV3;
#[async_trait]
impl NativeSigner for AcmeV3 {
async fn sign(
&self,
_auth: &AuthDef,
cred: &ResolvedCredential,
req: SignRequest<'_>,
) -> Result<(), NodeError> {
let key_id = cred.field_str("key_id").ok_or_else(|| NodeError::credential("missing key ID"))?;
let signature = acme_v3_signature(cred, req.method, req.url, req.body)?;
set_header(req.headers, "X-Acme-Key", key_id.to_string());
set_header(req.headers, "X-Acme-Signature", signature);
Ok(())
}
}
pub fn register() {
register_signer("acme_tasks::acme_v3_signature", std::sync::Arc::new(AcmeV3));
}
The signer runs on every attempt, including retries, so time-based signatures stay fresh.
Testing hooks
Native operations are tested with the same cassettes as declarative ones: the
hook’s requests go to the cassette’s mock server and are matched against exchanges. Add Rust
unit tests for any parsing or computation inside the hook.
Keeping the native share low
Each connector’s ratio of native to declarative operations is tracked. A connector above 50 percent native triggers a review of the connector format: if several connectors need the same hook, that is a missing YAML feature, and adding it helps every connector.