Aparência
SDK Rust
O crate stackchat-plugin-sdk gera a ABI stackchat.plugin.v1: os exports e imports que a plataforma exige, a leitura da invocação, a escrita do resultado e as chamadas ao host. O scplugin new copia o SDK para vendor/ do projeto; não é preciso acesso a nenhum repositório.
toml
[lib]
crate-type = ["cdylib"]
[dependencies]
stackchat-plugin-sdk = { path = "vendor/stackchat-plugin-sdk" }- Rust 1.82 ou mais novo, alvo
wasm32-unknown-unknown. - Feature padrão
oom-signal: instala um alocador global que avisa a plataforma quando falta memória, para a execução sair comoMemoryExceededem vez de um trap genérico. Desligue (default-features = false) só se o plugin precisa do próprio#[global_allocator].
Visão geral
| Item | Para quê | Permissão |
|---|---|---|
export_plugin! | Registra o handler | |
Invocation | O que chega a cada evento | |
PluginResult | O que o handler devolve | |
ActionProposal | Ações propostas | contacts.tag, messages.reply |
Error e HostError | Erros | |
events | Payloads tipados | messages.read para o texto |
kv | Chave-valor | storage.kv |
doc | Documentos JSON | storage.documents |
tables | Tabelas gerenciadas | storage.tables.read, storage.tables.write |
config | Configuração da instalação | config.read:<chave> |
http | Saída de rede | http.egress:<domínio> |
log | Logs | nenhuma |
testing | Host falso para cargo test (só fora do wasm) | |
call e abi | Baixo nível |
A raiz do crate também reexporta serde_json, a macro json! e o tipo Value, e a constante ABI ("stackchat.plugin.v1").
export_plugin!
rust
export_plugin!(handler);
// handler: fn(Invocation) -> Result<PluginResult, Error>, função ou closure sem capturaExporta stackchat_alloc e stackchat_invoke e liga o handler. Use uma vez por crate.
rust
use stackchat_plugin_sdk::{export_plugin, Error, Invocation, PluginResult};
fn handle(invocation: Invocation) -> Result<PluginResult, Error> {
stackchat_plugin_sdk::log::info(&format!("hook {}", invocation.hook));
Ok(PluginResult::pass())
}
export_plugin!(handle);export_alloc!() exporta só stackchat_alloc, para quem implementa stackchat_invoke à mão com o módulo abi.
Invocation
rust
pub struct Invocation {
pub abi: String,
pub hook: String, // "message.received.v1"...
pub execution_id: String, // muda a cada execução
pub event_id: String, // igual em todas as entregas do evento
pub payload: Value, // já filtrado pelas permissões
}
impl Invocation {
pub fn event(&self) -> Result<events::Event, Error>;
pub fn payload_as<T: DeserializeOwned>(&self) -> Result<T, Error>;
pub fn idempotency_key(&self, scope: &str) -> String; // "<eventId>:<scope>"
}rust
let message: MessageReceived = invocation.payload_as()?;
let chave = invocation.idempotency_key("criar-lead");PluginResult
rust
pub struct PluginResult {
pub abi: String,
pub decision: Decision, // Decision::Pass | Decision::Reject
pub actions: Vec<ActionProposal>,
pub reason: Option<String>,
pub transform: Option<Transform>, // Transform { text: String }
}
impl PluginResult {
pub fn pass() -> Self;
pub fn reject(reason: impl Into<String>) -> Self;
pub fn transform(text: impl Into<String>) -> Self; // só em message.outbound.prepare.v1
pub fn with_action(self, action: ActionProposal) -> Self;
}rust
Ok(PluginResult::pass())
Ok(PluginResult::pass().with_action(ActionProposal::contact_tag_add("tag", contact_id, "lead")))
Ok(PluginResult::reject("Fora do horário comercial."))
Ok(PluginResult::transform(format!("{text}\n\nEquipe Acme")))reject não leva ações. transform só vale em message.outbound.prepare.v1. Regras completas em Ações e Eventos.
ActionProposal
rust
pub struct ActionProposal {
pub action_type: String, // serializado como "type"
pub target: BTreeMap<String, String>,
pub payload: Value,
pub action_key: String,
}
impl ActionProposal {
pub fn contact_tag_add(action_key: impl Into<String>, contact_id: impl Into<String>, tag: impl Into<String>) -> Self;
pub fn message_reply_create(action_key: impl Into<String>, conversation_id: impl Into<String>, text: impl Into<String>) -> Self;
// Genéricos
pub fn new(action_type: impl Into<String>, action_key: impl Into<String>) -> Self;
pub fn target(self, key: impl Into<String>, value: impl Into<String>) -> Self;
pub fn payload(self, payload: Value) -> Self;
}As constantes dos tipos ficam em actions: actions::CONTACT_TAG_ADD ("contact.tag.add.v1") e actions::MESSAGE_REPLY_CREATE ("message.reply.create.v1").
rust
let resposta = ActionProposal::message_reply_create("reply", conversation_id, "Já te respondemos!");
// equivale a:
let resposta = ActionProposal::new(actions::MESSAGE_REPLY_CREATE, "reply")
.target("conversationId", conversation_id)
.payload(json!({ "text": "Já te respondemos!" }));A action_key precisa ser fixa para o mesmo efeito e única no resultado (Ações).
Error
rust
pub struct Error(/* mensagem */);
impl Error {
pub fn new(message: impl Into<String>) -> Self;
}
// From<HostError>, From<serde_json::Error>, From<&str>, From<String>Um Err do handler termina a execução como falha do plugin, com a mensagem no log. O ? converte HostError e erros de serde automaticamente.
HostError
rust
pub struct HostError {
pub code: String,
pub message: String,
}
impl HostError {
pub fn is(&self, code: &str) -> bool;
pub fn is_http(&self) -> bool; // código começa com "http."
}Códigos estáveis: capability_denied, not_found, conflict, quota_exceeded, invalid_request, unknown_operation, host_call_limit, unavailable e os http.* (Saída de rede). O SDK usa invalid_response quando não entende a resposta da plataforma.
rust
match tables::update("points", &id, &json!({ "points": 2 }), Some(versao)) {
Ok(_) => {}
Err(e) if e.is("conflict") => { /* releia e tente de novo */ }
Err(e) => return Err(e.into()),
}events
rust
pub enum Event {
MessageReceived(MessageReceived),
MessageOutboundPrepare(MessageOutboundPrepare),
ContactCreated(ContactChanged),
ContactUpdated(ContactChanged),
ConversationClosed(ConversationClosed),
Unknown, // hook mais novo que este SDK
}
pub struct MessageReceived {
pub message_id: String,
pub conversation_id: String,
pub channel_id: String,
pub channel_type: String,
pub contact_id: Option<String>,
pub kind: String,
pub text: Option<String>, // só com messages.read
pub sent_at: String,
}
pub struct MessageOutboundPrepare {
pub message_id: String,
pub conversation_id: String,
pub channel_id: String,
pub channel_type: String,
pub contact_id: Option<String>,
pub text: Option<String>, // só com messages.prepare
pub sent_at: String,
}
pub struct ContactChanged { pub contact_id: String }
pub struct ConversationClosed {
pub conversation_id: String,
pub channel_id: String,
pub contact_id: Option<String>,
}Constantes com os nomes dos hooks: MESSAGE_RECEIVED, MESSAGE_OUTBOUND_PREPARE, CONTACT_CREATED, CONTACT_UPDATED e CONVERSATION_CLOSED.
rust
use stackchat_plugin_sdk::events::Event;
let Event::ConversationClosed(conversa) = invocation.event()? else {
return Ok(PluginResult::pass());
};Campos e quando cada hook dispara: Eventos.
kv
rust
pub fn get(key: &str) -> Result<Option<Vec<u8>>, HostError>;
pub fn get_string(key: &str) -> Result<Option<String>, HostError>;
pub fn set(key: &str, value: &[u8]) -> Result<(), HostError>;
pub fn set_with_ttl(key: &str, value: &[u8], ttl_seconds: u32) -> Result<(), HostError>;
pub fn delete(key: &str) -> Result<(), HostError>;rust
let total = kv::get_string("total")?.and_then(|v| v.parse::<u64>().ok()).unwrap_or(0) + 1;
kv::set("total", total.to_string().as_bytes())?;
kv::set_with_ttl("cooldown", b"1", 600)?;Chave até 256 caracteres, valor até 64 KiB, TTL até 30 dias (Armazenamento).
doc
rust
pub struct Document { pub document: Value, pub version: i64 }
pub struct ListItem { pub id: String, pub version: i64, pub document: Value }
pub struct ListResult { pub items: Vec<ListItem>, pub next_cursor: Option<String> }
pub fn get(collection: &str, id: &str) -> Result<Option<Document>, HostError>;
pub fn put(collection: &str, id: &str, document: &Value, expected_version: Option<i64>) -> Result<i64, HostError>;
pub fn delete(collection: &str, id: &str, expected_version: Option<i64>) -> Result<(), HostError>;
pub fn list(collection: &str, prefix: Option<&str>, cursor: Option<&str>, limit: u32) -> Result<ListResult, HostError>;expected_version: None grava sem conferir, Some(0) só cria, outro valor exige a versão atual (senão conflict). put devolve a nova versão.
rust
let versao = doc::put("leads", &contact_id, &json!({ "etapa": "novo" }), Some(0))?;
let pagina = doc::list("leads", None, None, 100)?;tables
rust
pub struct Row { pub id: String, pub version: i64, pub created_at: String, pub updated_at: String, pub values: Value }
pub struct Page { pub rows: Vec<Row>, pub next_cursor: Option<String> }
pub struct WriteResult { pub id: String, pub version: i64 }
pub fn get(table: &str, id: &str) -> Result<Option<Row>, HostError>;
pub fn query(query: &Query) -> Result<Page, HostError>;
pub fn insert(table: &str, values: &Value, id: Option<&str>, idempotency_key: Option<&str>) -> Result<WriteResult, HostError>;
pub fn update(table: &str, id: &str, patch: &Value, expected_version: Option<i64>) -> Result<WriteResult, HostError>;
pub fn delete(table: &str, id: &str, expected_version: Option<i64>) -> Result<WriteResult, HostError>;
pub fn transaction(operations: &[Operation], idempotency_key: Option<&str>) -> Result<Vec<WriteResult>, HostError>;Query
rust
impl Query {
pub fn new(table: impl Into<String>) -> Self;
pub fn filter(self, filter: Filter) -> Self;
pub fn sort(self, column: impl Into<String>, descending: bool) -> Self; // até 2
pub fn cursor(self, cursor: impl Into<String>) -> Self;
pub fn limit(self, limit: u32) -> Self; // 1 a 200; padrão 50
}Filter
rust
impl Filter {
pub fn and(filters: Vec<Filter>) -> Self;
pub fn or(filters: Vec<Filter>) -> Self;
pub fn not(filter: Filter) -> Self;
pub fn eq(column: impl Into<String>, value: Value) -> Self; // também ne, lt, lte, gt, gte
pub fn prefix(column: impl Into<String>, value: impl Into<String>) -> Self; // só string
pub fn is_in(column: impl Into<String>, values: Vec<Value>) -> Self; // 1 a 100 valores
pub fn is_null(column: impl Into<String>) -> Self;
}Operation (para transaction, até 25, tudo ou nada)
rust
impl Operation {
pub fn insert(table: impl Into<String>, id: Option<&str>, values: Value) -> Self;
pub fn update(table: impl Into<String>, id: impl Into<String>, patch: Value, expected_version: Option<i64>) -> Self;
pub fn delete(table: impl Into<String>, id: impl Into<String>, expected_version: Option<i64>) -> Self;
}rust
use stackchat_plugin_sdk::tables::{self, Filter, Operation, Query};
let pagina = tables::query(
&Query::new("points")
.filter(Filter::and(vec![Filter::prefix("contact_ref", "c-"), Filter::gte("points", json!(5))]))
.sort("points", true)
.limit(20),
)?;
let resultados = tables::transaction(
&[
Operation::insert("ledger", None, json!({ "amount": "1.50" })),
Operation::delete("points", "x", Some(3)),
],
Some(invocation.idempotency_key("ledger").as_str()),
)?;Esquema, tipos e regras em Armazenamento.
config
rust
pub fn get(key: &str) -> Result<Option<String>, HostError>;None quando o campo não foi preenchido. Segredos nunca voltam (Configuração).
rust
let tag = config::get("tag")?.unwrap_or_else(|| "lead".to_owned());http
rust
pub const OPERATION: &str = "http.fetch";
pub const IDEMPOTENCY_HEADER: &str = "Idempotency-Key";
pub fn fetch(request: &Request) -> Result<Response, HostError>;
impl Request {
pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self;
pub fn get(url: impl Into<String>) -> Self;
pub fn post(url: impl Into<String>) -> Self;
pub fn header(self, name: impl Into<String>, value: impl Into<String>) -> Self;
pub fn secret_header(self, name: impl Into<String>, secret_key: impl Into<String>) -> Self;
pub fn idempotent(self, invocation: &Invocation, scope: &str) -> Self;
pub fn body(self, body: impl Into<String>) -> Self;
pub fn timeout_ms(self, timeout_ms: u32) -> Self;
}
pub struct Response { pub status: u16, pub headers: BTreeMap<String, String>, pub body: String, pub truncated: bool }
impl Response {
pub fn is_success(&self) -> bool; // 200 a 299
pub fn json<T: DeserializeOwned>(&self) -> Result<T, serde_json::Error>;
}Para PUT, PATCH e DELETE, use Request::new("PUT", url).
rust
let resposta = http::fetch(
&http::Request::get("https://api.crm-da-acme.com/v1/precos").secret_header("Authorization", "crm_token"),
)?;
if resposta.is_success() {
let precos: Value = resposta.json()?;
}Regras, limites e códigos em Saída de rede.
log
rust
pub fn debug(message: &str);
pub fn info(message: &str);
pub fn warn(message: &str);
pub fn error(message: &str);Não registre texto de mensagem nem dados pessoais. A plataforma corta linhas longas e limita as linhas por execução (Limites).
testing
Só existe fora do wasm, para cargo test. O host falso fica numa variável por thread: chame install no começo de cada teste.
rust
pub fn invoke<F>(handler: F, hook: &str, payload: Value) -> Result<PluginResult, Error>
where F: FnOnce(Invocation) -> Result<PluginResult, Error>;
impl MockHost {
pub fn new() -> Self;
pub fn with_kv(self, key: &str, value: &[u8]) -> Self;
pub fn with_config(self, key: &str, value: &str) -> Self;
pub fn with_http_response(self, response: Value) -> Self; // fila de respostas de http.fetch
pub fn on(self, operation: &str, handler: impl Fn(&Value) -> Result<Value, HostError> + 'static) -> Self;
pub fn fail(self, operation: &str, code: &str, message: &str) -> Self;
pub fn install(self);
pub fn calls() -> Vec<HostCall>; // HostCall { operation, request }
pub fn logs() -> Vec<LogLine>; // LogLine { level, message }
pub fn kv(key: &str) -> Option<Vec<u8>>;
}O MockHost guarda kv e documentos em memória, responde config.get com o que foi definido e devolve as respostas HTTP gravadas. on trata qualquer operação (use para tables.*); fail faz uma operação sempre falhar com o código dado. Operação sem tratamento responde unknown_operation. O MockHost não confere permissões: para isso, use scplugin test.
rust
#[test]
fn etiqueta_o_contato() {
use stackchat_plugin_sdk::json;
use stackchat_plugin_sdk::testing::{invoke, MockHost};
MockHost::new().with_config("tag", "lead").install();
let result = invoke(handle, "contact.created.v1", json!({ "contactId": "c-1" })).unwrap();
assert_eq!(result.actions.len(), 1);
}
#[test]
fn conflito_vira_erro() {
MockHost::new().fail("tables.update", "conflict", "versão diferente").install();
// ...
}invoke usa ids fixos para executionId e eventId.
call
rust
pub fn call(operation: &str, request: &Value) -> Result<Value, HostError>;Chama uma operação do host com o pedido JSON cru e devolve o result. Útil para operações que o SDK ainda não embrulha.
rust
let pagina = call("tables.query", &json!({ "table": "points", "limit": 1 }))?;abi
Transporte de baixo nível, para quem precisa controlar os bytes (fixtures, plugins sem serde). Quase todo plugin usa só export_plugin!.
rust
pub fn log_raw(level: i32, message: &[u8]); // 0 debug, 1 info, 2 warn, 3 error
pub fn call_raw(operation: &str, request: &[u8]) -> Vec<u8>;
pub fn alloc(len: i32) -> i32;
pub fn pack(ptr: u32, len: u32) -> i64;
pub fn unpack(packed: i64) -> (u32, u32);
pub fn leak_output(bytes: Vec<u8>) -> i64;
pub fn fail(message: &str) -> !;O módulo final só pode importar stackchat.host_log e stackchat.host_call. Qualquer outro import (WASI, env) recusa o módulo na validação.