salamandr-plugin-sdk 0.3.0

Write Salamandr helpdesk extensions in Rust: safe typed wrappers for every host capability, the fetch_context wire contract, and an in-process mock host for testing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! Typed access to the tenant's own helpdesk data — ticket types,
//! statuses, priorities, tags, users, organizations, teams, SLA policies,
//! custom fields, business hours and tickets. The guest half of
//! internal/extwasm/core.go; every function here is one `host_core` call
//! with the resource/action pair filled in.
//!
//! # Scopes
//!
//! Each function's doc comment names the `scopes.core` entry its
//! manifest must declare. Read and write are separate grants and neither
//! implies the other, so a plugin that only tags tickets cannot also read
//! every ticket in the tenant:
//!
//! ```toml
//! [scopes]
//! core = ["ticket_types:read", "users:read", "tags:read", "tags:write"]
//! ```
//!
//! Calling a resource the manifest didn't declare is an `Err`, not an
//! empty result — a plugin can tell "not allowed" from "this tenant has
//! none" without guessing.
//!
//! # Missing rows
//!
//! Every single-row lookup answers `Ok(None)` when the row doesn't
//! exist, so a plugin never pattern-matches an error string to find out.
//! Lists answer a [`Page`], whose `has_more` says whether another page
//! is worth asking for.

pub mod model;

pub use model::*;

use serde::Serialize;

use crate::error::HostError;
use crate::host::core_call;

const TICKETS: &str = "tickets";
const TICKET_TYPES: &str = "ticket_types";
const TICKET_STATUSES: &str = "ticket_statuses";
const TICKET_PRIORITIES: &str = "ticket_priorities";
const TAGS: &str = "tags";
const USERS: &str = "users";
const ORGANIZATIONS: &str = "organizations";
const TEAMS: &str = "teams";
const SLA_POLICIES: &str = "sla_policies";
const CUSTOM_FIELDS: &str = "custom_fields";
const BUSINESS_HOURS: &str = "business_hours";
const MEETINGS: &str = "meetings";

/// Paging is what every list function takes. `Paging::default()` asks for
/// the host's own default page (50); the host clamps anything above its
/// maximum (200) rather than serving it, so asking for a million rows
/// yields a page, never a table scan.
#[derive(Debug, Clone, Copy, Default, Serialize)]
pub struct Paging {
    #[serde(skip_serializing_if = "is_zero")]
    pub limit: i32,
    #[serde(skip_serializing_if = "is_zero")]
    pub offset: i32,
}

impl Paging {
    pub fn new(limit: i32, offset: i32) -> Self {
        Self { limit, offset }
    }

    /// page(n) is the nth page (0-based) of `limit`-sized pages — the
    /// arithmetic every caller would otherwise write inline.
    pub fn page(limit: i32, page: i32) -> Self {
        Self { limit, offset: limit.saturating_mul(page) }
    }
}

fn is_zero(v: &i32) -> bool {
    *v == 0
}

/// none is the "this action takes no params" argument. Spelled out rather
/// than `None` so the type inference at each call site stays local.
fn none() -> Option<()> {
    None
}

/// opt turns a host "not found" into Ok(None) — the shape every
/// single-row lookup below shares.
fn opt<T>(res: Result<T, HostError>) -> Result<Option<T>, HostError> {
    match res {
        Ok(v) => Ok(Some(v)),
        Err(e) if e.is_not_found() => Ok(None),
        Err(e) => Err(e),
    }
}

// ---------------------------------------------------------------------
// Reference data.
// ---------------------------------------------------------------------

/// Every ticket type the tenant defined. Requires `ticket_types:read`.
pub fn ticket_types() -> Result<Page<TicketType>, HostError> {
    core_call(TICKET_TYPES, "list", none())
}

/// Every ticket status, in the tenant's own sort order. Requires
/// `ticket_statuses:read`.
pub fn ticket_statuses() -> Result<Page<TicketStatus>, HostError> {
    core_call(TICKET_STATUSES, "list", none())
}

/// Every ticket priority. Requires `ticket_priorities:read`.
pub fn ticket_priorities() -> Result<Page<TicketPriority>, HostError> {
    core_call(TICKET_PRIORITIES, "list", none())
}

/// Every SLA policy. Requires `sla_policies:read`.
pub fn sla_policies() -> Result<Page<SlaPolicy>, HostError> {
    core_call(SLA_POLICIES, "list", none())
}

#[derive(Serialize)]
struct PriorityParams<'a> {
    priority_id: &'a str,
}

/// The SLA policy that applies to one priority, or None if the tenant
/// defined none. Requires `sla_policies:read`.
pub fn sla_policy_for_priority(priority_id: &str) -> Result<Option<SlaPolicy>, HostError> {
    opt(core_call(SLA_POLICIES, "for_priority", Some(PriorityParams { priority_id })))
}

#[derive(Default, Serialize)]
struct CustomFieldParams<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    entity: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    active_only: Option<bool>,
}

/// The tenant's custom-field definitions for one entity ("ticket",
/// "customer" or "organization"; None means "ticket"). `active_only`
/// defaults host-side to only the live ones. Requires
/// `custom_fields:read`.
pub fn custom_fields(entity: Option<&str>, active_only: Option<bool>) -> Result<Page<CustomField>, HostError> {
    core_call(CUSTOM_FIELDS, "list", Some(CustomFieldParams { entity, active_only }))
}

/// The tenant's working calendar — the same weekly windows and holidays
/// real SLA deadlines are computed against, so a plugin quoting a due
/// date can quote the one the helpdesk will actually use. Check
/// `enabled` first. Requires `business_hours:read`.
pub fn business_hours() -> Result<BusinessHours, HostError> {
    core_call(BUSINESS_HOURS, "get", none())
}

// ---------------------------------------------------------------------
// Tags.
// ---------------------------------------------------------------------

/// Every tag in the tenant's vocabulary. Requires `tags:read`.
pub fn tags() -> Result<Page<Tag>, HostError> {
    core_call(TAGS, "list", none())
}

#[derive(Serialize)]
struct TicketParams<'a> {
    ticket_id: &'a str,
}

/// The tags currently on one ticket. Requires `tags:read`.
pub fn ticket_tags(ticket_id: &str) -> Result<Page<Tag>, HostError> {
    core_call(TAGS, "for_ticket", Some(TicketParams { ticket_id }))
}

#[derive(Serialize)]
struct TicketTagsParams<'a> {
    ticket_id: &'a str,
    names: &'a [&'a str],
}

/// Adds tags to a ticket by *name*, creating any the tenant doesn't have
/// yet — the same case-insensitive create-on-write tagging works with
/// everywhere else here. At most 20 names per call. Answers the ticket's
/// resulting tag set. Requires `tags:write`.
pub fn add_ticket_tags(ticket_id: &str, names: &[&str]) -> Result<Page<Tag>, HostError> {
    core_call(TAGS, "add_to_ticket", Some(TicketTagsParams { ticket_id, names }))
}

/// Removes tags from a ticket by name (the vocabulary entry itself
/// stays). Answers the ticket's resulting tag set. Requires
/// `tags:write`.
pub fn remove_ticket_tags(ticket_id: &str, names: &[&str]) -> Result<Page<Tag>, HostError> {
    core_call(TAGS, "remove_from_ticket", Some(TicketTagsParams { ticket_id, names }))
}

// ---------------------------------------------------------------------
// People.
// ---------------------------------------------------------------------

#[derive(Serialize)]
struct ListUsersParams<'a> {
    #[serde(flatten)]
    paging: Paging,
    #[serde(skip_serializing_if = "Option::is_none")]
    role: Option<&'a str>,
}

/// Users in this tenant, optionally filtered to one role ("admin",
/// "agent" or "customer"). Requires `users:read`.
pub fn users(paging: Paging, role: Option<&str>) -> Result<Page<User>, HostError> {
    core_call(USERS, "list", Some(ListUsersParams { paging, role }))
}

#[derive(Serialize)]
struct UserIdParams<'a> {
    user_id: &'a str,
}

/// One user by id. Requires `users:read`.
pub fn user(user_id: &str) -> Result<Option<User>, HostError> {
    opt(core_call(USERS, "get", Some(UserIdParams { user_id })))
}

#[derive(Serialize)]
struct EmailParams<'a> {
    email: &'a str,
}

/// One user by email address — matches alternate addresses too, the same
/// way inbound email does. Requires `users:read`.
pub fn user_by_email(email: &str) -> Result<Option<User>, HostError> {
    opt(core_call(USERS, "by_email", Some(EmailParams { email })))
}

#[derive(Serialize)]
struct OrganizationIdParams<'a> {
    organization_id: &'a str,
    #[serde(flatten)]
    paging: Paging,
}

/// Organizations in this tenant. Requires `organizations:read`.
pub fn organizations(paging: Paging) -> Result<Page<Organization>, HostError> {
    core_call(ORGANIZATIONS, "list", Some(paging))
}

/// One organization by id. Requires `organizations:read`.
pub fn organization(organization_id: &str) -> Result<Option<Organization>, HostError> {
    opt(core_call(
        ORGANIZATIONS,
        "get",
        Some(OrganizationIdParams { organization_id, paging: Paging::default() }),
    ))
}

/// One organization by the email domain it claims. Requires
/// `organizations:read`.
pub fn organization_by_domain(domain: &str) -> Result<Option<Organization>, HostError> {
    #[derive(Serialize)]
    struct DomainParams<'a> {
        domain: &'a str,
    }
    opt(core_call(ORGANIZATIONS, "by_domain", Some(DomainParams { domain })))
}

/// The users belonging to one organization. Requires
/// `organizations:read`.
pub fn organization_members(organization_id: &str, paging: Paging) -> Result<Page<User>, HostError> {
    core_call(ORGANIZATIONS, "members", Some(OrganizationIdParams { organization_id, paging }))
}

/// The tenant's teams. Requires `teams:read`.
pub fn teams(paging: Paging) -> Result<Page<Team>, HostError> {
    core_call(TEAMS, "list", Some(paging))
}

/// The agents on one team. Requires `teams:read`.
pub fn team_members(team_id: &str) -> Result<Page<User>, HostError> {
    #[derive(Serialize)]
    struct TeamIdParams<'a> {
        team_id: &'a str,
    }
    core_call(TEAMS, "members", Some(TeamIdParams { team_id }))
}

// ---------------------------------------------------------------------
// Tickets.
// ---------------------------------------------------------------------

/// One ticket by id. Requires `tickets:read`.
pub fn ticket(ticket_id: &str) -> Result<Option<Ticket>, HostError> {
    opt(core_call(TICKETS, "get", Some(TicketParams { ticket_id })))
}

#[derive(Serialize)]
struct RequesterParams<'a> {
    requester_id: &'a str,
    #[serde(flatten)]
    paging: Paging,
}

/// A requester's tickets, newest first. Requires `tickets:read`.
pub fn tickets_by_requester(requester_id: &str, paging: Paging) -> Result<Page<Ticket>, HostError> {
    core_call(TICKETS, "list_by_requester", Some(RequesterParams { requester_id, paging }))
}

/// An organization's tickets, newest first. Requires `tickets:read`.
pub fn tickets_by_organization(organization_id: &str, paging: Paging) -> Result<Page<Ticket>, HostError> {
    core_call(
        TICKETS,
        "list_by_organization",
        Some(OrganizationIdParams { organization_id, paging }),
    )
}

#[derive(Serialize)]
struct MessagesParams<'a> {
    ticket_id: &'a str,
    #[serde(skip_serializing_if = "is_false")]
    include_private: bool,
}

fn is_false(v: &bool) -> bool {
    !*v
}

/// A ticket's conversation. `include_private` opts into internal notes
/// and is off by default: the common case is a plugin summarising what
/// the customer actually wrote, and staff-only commentary reaching a
/// third-party system is the accident that default prevents. Requires
/// `tickets:read`.
pub fn ticket_messages(ticket_id: &str, include_private: bool) -> Result<Page<TicketMessage>, HostError> {
    core_call(TICKETS, "messages", Some(MessagesParams { ticket_id, include_private }))
}

#[derive(Serialize)]
struct AddNoteParams<'a> {
    ticket_id: &'a str,
    author_id: &'a str,
    body: &'a str,
}

#[derive(serde::Deserialize)]
struct AddNoteResult {
    message_id: String,
}

/// Posts an internal (staff-only, never customer-visible) note onto a
/// ticket's conversation and answers the new message's id.
///
/// `author_id` is required because `ticket_messages.author_id` is NOT
/// NULL and there is no "the plugin" user row — pick one with
/// [`user_by_email`] (typically an agent the extension's own config
/// names). At most 16 KiB of body. Requires `tickets:write`.
pub fn add_ticket_note(ticket_id: &str, author_id: &str, body: &str) -> Result<String, HostError> {
    let res: AddNoteResult = core_call(TICKETS, "add_note", Some(AddNoteParams { ticket_id, author_id, body }))?;
    Ok(res.message_id)
}

#[derive(Serialize)]
struct UpdateTicketParams<'a> {
    ticket_id: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    status_id: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    priority_id: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    assigned_agent_id: Option<&'a str>,
}

/// TicketUpdate is the state a plugin may move on an existing ticket.
/// Build one with [`TicketUpdate::new`] and set only what changes; an
/// unset field is left alone.
#[derive(Debug, Clone, Default)]
pub struct TicketUpdate<'a> {
    pub status_id: Option<&'a str>,
    pub priority_id: Option<&'a str>,
    pub assigned_agent_id: Option<&'a str>,
}

impl<'a> TicketUpdate<'a> {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn status(mut self, id: &'a str) -> Self {
        self.status_id = Some(id);
        self
    }
    pub fn priority(mut self, id: &'a str) -> Self {
        self.priority_id = Some(id);
        self
    }
    pub fn assign(mut self, agent_id: &'a str) -> Self {
        self.assigned_agent_id = Some(agent_id);
        self
    }
}

/// Moves an existing ticket's state — the outside system closing the loop.
///
/// This is what a connector uses when its vendor says the work is done: an
/// issue tracker's issue closed, a monitoring alert resolved, a work order
/// dispatched. Before it existed such a connector could only post a note
/// saying so and leave a human to change the ticket.
///
/// It goes through the same path an agent's own edit does, so the
/// ticket_events rows, SLA recalculation, outbound webhooks and
/// notifications are identical.
///
/// Deliberately state only. The subject and the summary are what a human
/// wrote about the problem — say your piece with [`add_ticket_note`]
/// instead of rewriting theirs — and the requester is an authorization
/// decision, not one to make from a webhook payload. Ids are resolved with
/// [`ticket_statuses`], [`ticket_priorities`] and [`users`]. Requires
/// `tickets:write`.
pub fn update_ticket(ticket_id: &str, update: TicketUpdate<'_>) -> Result<(), HostError> {
    let _: serde_json::Value = core_call(
        TICKETS,
        "update",
        Some(UpdateTicketParams {
            ticket_id,
            status_id: update.status_id,
            priority_id: update.priority_id,
            assigned_agent_id: update.assigned_agent_id,
        }),
    )?;
    Ok(())
}

#[derive(Serialize)]
struct CreateTicketParams<'a> {
    requester_id: &'a str,
    subject: &'a str,
    #[serde(skip_serializing_if = "str::is_empty")]
    body: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    ticket_type_id: Option<&'a str>,
}

#[derive(serde::Deserialize)]
struct CreateTicketResult {
    ticket_id: String,
}

/// Files a new ticket and answers its id.
///
/// This is what a connector reporting *new work* uses — a monitoring
/// system's outage, an ERP's failed payment run, a tracker's regression —
/// as opposed to [`add_ticket_note`], which comments on work the helpdesk
/// already knows about. Typically called from `webhook_receive`.
///
/// It goes through the same path an agent's own "new ticket" does, so
/// routing rules, SLA, outbound webhooks and notifications all apply.
/// Three things the host decides rather than you:
///
/// * The channel is always `"extension"` — a plugin cannot claim a
///   ticket arrived by email.
/// * The customer gets no "your ticket was created" email and the body
///   lands as an internal note, since nobody asked for this ticket and
///   the body is machine-written.
/// * Priority comes from the tenant's default and then its routing
///   rules, which is where an admin can see and change it.
///
/// `requester_id` must name an existing user — resolve one with
/// [`user_by_email`], or use the service account your extension's config
/// names. Creating users from here is deliberately not possible.
///
/// `ticket_type_id` empty means the tenant's default type. Subject is
/// capped at 500 bytes, body at 16 KiB. Requires `tickets:write`.
pub fn create_ticket(
    requester_id: &str,
    subject: &str,
    body: &str,
    ticket_type_id: Option<&str>,
) -> Result<String, HostError> {
    let res: CreateTicketResult = core_call(
        TICKETS,
        "create",
        Some(CreateTicketParams { requester_id, subject, body, ticket_type_id }),
    )?;
    Ok(res.ticket_id)
}

#[derive(Serialize)]
struct UpsertCustomerParams<'a> {
    email: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    phone: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    organization_id: Option<&'a str>,
}

#[derive(serde::Deserialize)]
struct UpsertCustomerResult {
    user_id: String,
}

/// Creates or updates a customer, matched on their address, and answers
/// their user id.
///
/// The write half of keeping the helpdesk's own directory in step with a
/// CRM or ERP. Only ever touches *customers*: an address that already
/// belongs to an agent or admin is refused, because a vendor record is an
/// unverified claim about an identity and rewriting a staff account with
/// one would be identity manipulation rather than a sync.
///
/// A `None` field is left alone rather than blanked, so a connector that
/// knows a phone number but not a name doesn't erase the name. Creating a
/// customer does **not** consume a seat — the SaaS quota counts staff.
/// Requires `users:write`.
pub fn upsert_customer(
    email: &str,
    name: Option<&str>,
    phone: Option<&str>,
    organization_id: Option<&str>,
) -> Result<String, HostError> {
    let res: UpsertCustomerResult = core_call(
        USERS,
        "upsert",
        Some(UpsertCustomerParams { email, name, phone, organization_id }),
    )?;
    Ok(res.user_id)
}

#[derive(Serialize)]
struct UpsertOrganizationParams<'a> {
    name: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    domain: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    website: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    phone: Option<&'a str>,
}

#[derive(serde::Deserialize)]
struct UpsertOrganizationResult {
    organization_id: String,
}

/// Creates or updates an organization and answers its id.
///
/// Matched on `domain` when one is given — what a vendor sync keys on —
/// and on name otherwise, so a company with no domain on file doesn't get
/// duplicated on every pass. Pair with [`upsert_customer`]'s
/// `organization_id` to land a synced contact in the right company.
/// Requires `organizations:write`.
pub fn upsert_organization(
    name: &str,
    domain: Option<&str>,
    website: Option<&str>,
    phone: Option<&str>,
) -> Result<String, HostError> {
    let res: UpsertOrganizationResult = core_call(
        ORGANIZATIONS,
        "upsert",
        Some(UpsertOrganizationParams { name, domain, website, phone }),
    )?;
    Ok(res.organization_id)
}

#[derive(Serialize)]
struct ApplyExternalCalendarUpdateParams<'a> {
    external_event_id: &'a str,
    cancelled: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    new_start: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    new_end: Option<&'a str>,
}

/// Reports that a meeting this plugin mirrors moved or was cancelled on
/// the vendor's side — the reverse direction of
/// [`crate::calendar_sync`]'s `calendar_sync_meeting`/etc., for a plugin
/// that declared `scopes.calendar_sync`.
///
/// Typically called from `webhook_receive` (a vendor push notification)
/// or `scheduled_run` (a periodic reconciliation), after the plugin
/// re-fetches the changed event itself via [`crate::oauth_fetch`] to
/// decide what happened. `new_start`/`new_end` are RFC 3339; both `None`
/// with `cancelled: false` is accepted as a no-op, since a plugin that
/// re-fetched and found nothing changed shouldn't need a special case to
/// report that.
///
/// The provider this applies to is the calling plugin's own installed
/// identity — there is no provider parameter here, and none is needed:
/// the host resolves it from which extension is making the call, the same
/// way it stamps an action's actor/ticket rather than trusting the guest
/// to name them. Requires `meetings:write`.
pub fn apply_external_calendar_update(
    external_event_id: &str,
    cancelled: bool,
    new_start: Option<&str>,
    new_end: Option<&str>,
) -> Result<(), HostError> {
    let _: serde_json::Value = core_call(
        MEETINGS,
        "apply_external_update",
        Some(ApplyExternalCalendarUpdateParams { external_event_id, cancelled, new_start, new_end }),
    )?;
    Ok(())
}