Using another unit
A Plugin may ask another unit's questions and follow its streams, without knowing which unit it is. It declares that it needs a unit, and what it uses of it; the application binds the need to one of its Plugin units; an operator grants the use; and the Core hands the Plugin the path of a channel on which it is that unit's client. The Plugin speaks to that channel with its family's interface library — the same one an interface uses — and the unit it asks answers it as it answers any client.
The example on this page is com.example.agenda: it answers agenda.next with what is left of the day,
by asking the unit its need calendar is bound to the question calendar.events. In an application that
unit is the pool's calendar (a Plugin that uses another).
What it declares
manifest: 1
id: com.example.agenda
protocol: 1
needs:
- unit:calendar
queries:
- id: agenda.next
uses:
calendar:
questions:
- calendar.events
capabilities:
- name: query.agenda.next.answer
governs:
query: agenda.next
- name: query.calendar.events.ask
governs:
use:
need: calendar
query: calendar.events
| Declared | Says |
|---|---|
needs: unit:calendar | the Plugin uses another unit's contract, through a need it calls calendar |
uses.calendar | what it uses of that unit: the questions it asks, the streams it follows, in that unit's names. No commands: a unit never instructs another |
query.calendar.events.ask | the capability an operator grants for the use; a follow would be stream.<id>.follow |
A need of class unit is always bound. There is no optional need: an application that takes agenda
binds calendar to a unit, or the gate refuses it.
The program
The unit is given the channel's path in the argument it declared, ${bind.calendar}, and nothing
else — not the name of the unit behind it. It reads that name from the channel's opening, which shows the
one unit the channel may address. Asking while it answers, it names the question it answers as the
cause: the Core gives the inner question that one's chain, and its deadline less 500 ms, so the asker's
wait bounds the whole chain.
- Go
- Rust
- Python
- C
- C++
// Command agenda is a Plugin that answers what is next today, by asking the calendar its need is bound to.
package main
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/yoke-project/yoke-sdk-go/base"
"github.com/yoke-project/yoke-sdk-go/iface"
"github.com/yoke-project/yoke-sdk-go/plugin"
)
func declaration() plugin.Declaration {
return plugin.Declaration{
ID: "com.example.agenda",
Needs: []string{"unit:calendar"},
Queries: []string{"agenda.next"},
Uses: map[string]plugin.Use{"calendar": {Questions: []string{"calendar.events"}}},
Capabilities: []plugin.Capability{
{Name: "query.agenda.next.answer", Governs: plugin.Object{Query: "agenda.next"}},
{Name: "query.calendar.events.ask", Governs: plugin.Object{Use: &plugin.UseObject{Need: "calendar", Query: "calendar.events"}}},
},
}
}
func main() {
if len(os.Args) == 2 && os.Args[1] == "--manifest" {
os.Stdout.Write(declaration().Manifest())
return
}
if len(os.Args) != 3 || os.Args[1] != "--calendar" {
fmt.Fprintln(os.Stderr, "agenda: usage: agenda --calendar ${bind.calendar}")
os.Exit(2)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
u, err := plugin.Start(ctx, declaration())
if err != nil {
fmt.Fprintln(os.Stderr, "agenda:", err)
os.Exit(1)
}
// The need's channel: its opening shows the one unit it may address.
calendar, err := iface.Attach(ctx, os.Args[2])
if err != nil {
u.Health(50, "the calendar cannot be reached: "+err.Error())
u.Close()
<-u.Done()
os.Exit(1)
}
defer calendar.Close()
bound := ""
for _, r := range calendar.Picture.GetRecords() {
if id := r.GetUnit().GetDeclared().GetIdentity(); id != "" {
bound = id
break
}
}
u.Health(0, "asks "+bound)
for {
select {
case event, open := <-u.Events():
if !open {
return
}
if q, ok := event.(plugin.Question); ok && q.Type == "agenda.next" {
go answer(ctx, u, calendar, bound, q)
}
case <-ctx.Done():
u.Close()
<-u.Done()
return
}
}
}
// answer asks the calendar for the rest of the day, the question answered as the cause, and hands its
// answer on; a refusal is said in this Plugin's own words.
func answer(ctx context.Context, u *plugin.Unit, calendar *iface.Attachment, bound string, q plugin.Question) {
now := time.Now()
window := fmt.Sprintf(`{"from":%d,"to":%d}`, now.UnixMilli(), now.Add(24*time.Hour).UnixMilli())
events, err := calendar.AskCaused(ctx, q.ID, bound, "calendar.events", []byte(window))
var r *base.Refusal
switch {
case err == nil:
u.Answer(q, events)
case errors.As(err, &r):
u.Fail(q.ID, "calendar.refused", bound+" refused calendar.events: "+r.Code+" "+r.Item)
default:
u.Fail(q.ID, "calendar.unavailable", bound+" cannot be asked: "+err.Error())
}
}
//! agenda: a Plugin that answers what is next today, by asking the calendar its need is bound to.
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use yoke_proto::interface::v1::record::Subject;
use yoke_sdk::base::Error;
use yoke_sdk::interface::{Attachment, Options};
use yoke_sdk::plugin::{Capability, Declaration, Event, Object, Question, Unit, Use, start};
fn declaration() -> Declaration {
Declaration {
id: "com.example.agenda".into(),
needs: vec!["unit:calendar".into()],
queries: vec!["agenda.next".into()],
uses: BTreeMap::from([(
"calendar".into(),
Use {
questions: vec!["calendar.events".into()],
streams: vec![],
},
)]),
capabilities: vec![
Capability {
name: "query.agenda.next.answer".into(),
governs: Object::Query("agenda.next".into()),
},
Capability {
name: "query.calendar.events.ask".into(),
governs: Object::UseQuery("calendar".into(), "calendar.events".into()),
},
],
..Default::default()
}
}
/// Asks the calendar for the rest of the day, the question answered as the cause, and hands its answer on;
/// a refusal is said in this Plugin's own words.
async fn answer(unit: &Unit, calendar: &Attachment, bound: &str, q: &Question) {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let to = now + Duration::from_secs(86_400);
let window = format!(r#"{{"from":{},"to":{}}}"#, now.as_millis(), to.as_millis());
let _ = match calendar
.ask_caused(&q.id, bound, "calendar.events", window.as_bytes())
.await
{
Ok(events) => unit.answer(q, events).await,
Err(Error::Refusal(r)) => {
let why = format!(
"{bound} refused calendar.events: {} {}",
r.code,
r.item.unwrap_or_default()
);
unit.fail(&q.id, "calendar.refused", &why).await
}
Err(e) => {
unit.fail(
&q.id,
"calendar.unavailable",
&format!("{bound} cannot be asked: {e}"),
)
.await
}
};
}
#[tokio::main]
async fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args == ["--manifest"] {
print!("{}", declaration().manifest());
return;
}
let [flag, path] = args.as_slice() else {
eprintln!("agenda: usage: agenda --calendar ${{bind.calendar}}");
std::process::exit(2);
};
if flag != "--calendar" {
eprintln!("agenda: usage: agenda --calendar ${{bind.calendar}}");
std::process::exit(2);
}
let unit = match start(&declaration()).await {
Ok(u) => Arc::new(u),
Err(e) => {
eprintln!("agenda: {e}");
std::process::exit(1);
}
};
// The need's channel: its opening shows the one unit it may address.
let calendar = match Attachment::attach(path, Options::new()).await {
Ok(a) => Arc::new(a),
Err(e) => {
let _ = unit
.health(50, &format!("the calendar cannot be reached: {e}"))
.await;
std::process::exit(1);
}
};
let bound: Arc<str> = calendar
.picture
.records
.iter()
.find_map(|r| match &r.subject {
Some(Subject::Unit(u)) => u.declared.as_ref().map(|d| d.identity.clone()),
_ => None,
})
.unwrap_or_default()
.into();
let _ = unit.health(0, &format!("asks {bound}")).await;
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("agenda listens for SIGTERM");
loop {
tokio::select! {
event = unit.next() => match event {
None | Some(Event::Ended(_)) => return,
Some(Event::Question(q)) if q.r#type == "agenda.next" => {
let (unit, calendar, bound) = (unit.clone(), calendar.clone(), bound.clone());
tokio::spawn(async move { answer(&unit, &calendar, &bound, &q).await });
}
Some(_) => {}
},
_ = term.recv() => {
// Asked to stop: close the Session in order, and leave once it has ended.
let _ = unit.close().await;
while let Some(e) = unit.next().await {
if matches!(e, Event::Ended(_)) { break; }
}
return;
}
}
}
}
"""agenda: a Plugin that answers what is next today, by asking the calendar its need is bound to."""
import asyncio
import json
import signal
import sys
import time
from yoke_sdk import base, interface, plugin
def declaration():
return plugin.Declaration(
id="com.example.agenda",
needs=["unit:calendar"],
queries=["agenda.next"],
uses={"calendar": plugin.Use(questions=["calendar.events"])},
capabilities=[
plugin.Capability("query.agenda.next.answer", plugin.Object(query="agenda.next")),
plugin.Capability(
"query.calendar.events.ask",
plugin.Object(use=plugin.UseObject(need="calendar", query="calendar.events")),
),
],
)
async def answer(unit, calendar, bound, question):
"""Asks the calendar for the rest of the day, the question answered as the cause, and hands its
answer on; a refusal is said in this Plugin's own words."""
now = int(time.time() * 1000)
window = json.dumps({"from": now, "to": now + 86_400_000}).encode()
try:
events = await calendar.ask(bound, "calendar.events", window, cause=question.id)
except base.Refusal as r:
await unit.fail(question, "calendar.refused", f"{bound} refused calendar.events: {r.code} {r.item or ''}")
return
except base.Error as err:
await unit.fail(question, "calendar.unavailable", f"{bound} cannot be asked: {err}")
return
await unit.answer(question, events)
async def run(path):
unit = await plugin.start(declaration())
try:
# The need's channel: its opening shows the one unit it may address.
calendar = await interface.Attachment.attach(path)
except base.Error as err:
await unit.health(50, f"the calendar cannot be reached: {err}")
raise
bound = next(r.unit.declared.identity for r in calendar.picture.records if r.HasField("unit"))
await unit.health(0, f"asks {bound}")
stopping = asyncio.Event()
asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, stopping.set)
asked = asyncio.create_task(stopping.wait())
while True:
following = asyncio.create_task(unit.next())
done, _ = await asyncio.wait({following, asked}, return_when=asyncio.FIRST_COMPLETED)
if following in done:
event = following.result()
if event is None or isinstance(event, plugin.Ended):
return
if isinstance(event, plugin.Question) and event.type == "agenda.next":
asyncio.create_task(answer(unit, calendar, bound, event))
continue
following.cancel()
await unit.close()
while (event := await unit.next()) is not None and not isinstance(event, plugin.Ended):
pass
return
def main():
if sys.argv[1:] == ["--manifest"]:
sys.stdout.write(declaration().manifest())
return
if len(sys.argv) != 3 or sys.argv[1] != "--calendar":
print("agenda: usage: agenda --calendar ${bind.calendar}", file=sys.stderr)
sys.exit(2)
try:
asyncio.run(run(sys.argv[2]))
except base.Error as err:
print("agenda:", err, file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
/* agenda: a Plugin that answers what is next today, by asking the calendar its need is bound to. */
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <yoke/interface.h>
#include <yoke/plugin.h>
static const char *const needs[] = {"unit:calendar", NULL};
static const char *const queries[] = {"agenda.next", NULL};
static const char *const asked[] = {"calendar.events", NULL};
static const yoke_use uses[] = {{.need = "calendar", .questions = asked}, {0}};
static const yoke_capability capabilities[] = {
{.name = "query.agenda.next.answer", .governs = {YOKE_GOVERNS_QUERY, "agenda.next"}},
{.name = "query.calendar.events.ask", .governs = {YOKE_GOVERNS_USE_QUERY, "calendar.events", "calendar"}},
{0},
};
static const yoke_declaration declaration = {
.id = "com.example.agenda",
.needs = needs,
.queries = queries,
.uses = uses,
.capabilities = capabilities,
};
static volatile sig_atomic_t stopping;
static void on_term(int sig) { (void)sig; stopping = 1; }
/* The one unit the need's channel's opening shows. */
static const char *bound_unit(const yoke_attachment *calendar) {
const Yoke__Interface__V1__Snapshot *picture = yoke_picture(calendar);
for (size_t i = 0; picture != NULL && i < picture->n_records; i++)
if (picture->records[i]->subject_case == YOKE__INTERFACE__V1__RECORD__SUBJECT_UNIT)
return picture->records[i]->unit->declared->identity;
return NULL;
}
/* Asks the calendar for the rest of the day, the question answered as the cause, and hands its answer on;
a refusal is said in this Plugin's own words. */
static void answer(yoke_unit *unit, yoke_attachment *calendar, const char *bound, const yoke_event *q) {
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
long long ms = (long long)now.tv_sec * 1000 + now.tv_nsec / 1000000;
char window[64];
int len = snprintf(window, sizeof window, "{\"from\":%lld,\"to\":%lld}", ms, ms + 86400000LL);
Yoke__Interface__V1__Response *events = NULL;
yoke_error err = {0}, said = {0};
if (yoke_ask_caused(calendar, q->id, bound, "calendar.events", window, (size_t)len, &events, &err) == 0) {
yoke_answer(unit, q, events->query->payload.data, events->query->payload.len, &said);
yoke_response_free(events);
} else {
char why[512];
snprintf(why, sizeof why, "%s refused calendar.events: %s %s", bound, err.code ? err.code : err.message,
err.item ? err.item : "");
yoke_fail(unit, q->id, err.code ? "calendar.refused" : "calendar.unavailable", why, &said);
yoke_error_clear(&err);
}
yoke_error_clear(&said);
}
int main(int argc, char **argv) {
if (argc == 2 && strcmp(argv[1], "--manifest") == 0) {
char *manifest = yoke_manifest(&declaration);
fputs(manifest, stdout);
free(manifest);
return 0;
}
if (argc != 3 || strcmp(argv[1], "--calendar") != 0) {
fputs("agenda: usage: agenda --calendar ${bind.calendar}\n", stderr);
return 2;
}
signal(SIGTERM, on_term);
yoke_error err = {0};
yoke_unit *unit = yoke_start(&declaration, &err);
if (unit == NULL) {
fprintf(stderr, "agenda: %s\n", err.message);
yoke_error_clear(&err);
return 1;
}
/* The need's channel: its opening shows the one unit it may address. */
yoke_attachment *calendar = yoke_attach(argv[2], NULL, &err);
const char *bound = calendar != NULL ? bound_unit(calendar) : NULL;
if (bound == NULL) {
yoke_health(unit, 50, "the calendar cannot be reached", &err);
yoke_close(unit, &err);
yoke_free(unit);
return 1;
}
yoke_health(unit, 0, "asks the calendar", &err);
yoke_event event = {0};
while (!stopping) {
int got = yoke_next_within(unit, &event, 200);
if (got == 0)
break;
if (got == 1 && event.kind == YOKE_QUESTION && strcmp(event.type, "agenda.next") == 0)
answer(unit, calendar, bound, &event);
if (got == 1)
yoke_event_clear(&event);
}
if (stopping) {
yoke_close(unit, &err);
while (yoke_next(unit, &event) == 1)
yoke_event_clear(&event);
}
yoke_detach(calendar);
yoke_free(unit);
return 0;
}
// agenda: a Plugin that answers what is next today, by asking the calendar its need is bound to.
#include <atomic>
#include <chrono>
#include <csignal>
#include <iostream>
#include <memory>
#include <string>
#include <string_view>
#include <thread>
#include <variant>
#include <yoke/base.hpp>
#include <yoke/interface.hpp>
#include <yoke/plugin.hpp>
using namespace yoke::plugin;
Declaration declaration() {
return {
.id = "com.example.agenda",
.needs = {"unit:calendar"},
.queries = {"agenda.next"},
.capabilities = {{"query.agenda.next.answer", {Governs::query, "agenda.next"}},
{"query.calendar.events.ask", {Governs::use_query, "calendar.events", "calendar"}}},
.uses = {{"calendar", {.questions = {"calendar.events"}}}},
};
}
// The one unit the need's channel's opening shows.
static std::string bound_unit(const yoke::iface::Attachment &calendar) {
for (const auto &record : calendar.picture().records())
if (record.has_unit())
return record.unit().declared().identity();
return {};
}
// Asks the calendar for the rest of the day, the question answered as the cause, and hands its answer on;
// a refusal is said in this Plugin's own words.
static void answer(Unit &unit, yoke::iface::Attachment &calendar, const std::string &bound, const Question &q) {
using namespace std::chrono;
auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
auto window = "{\"from\":" + std::to_string(now) + ",\"to\":" + std::to_string(now + 86400000) + "}";
try {
unit.answer(q, calendar.ask_caused(q.id, bound, "calendar.events", window));
} catch (const yoke::Refusal &r) {
unit.fail(q.id, "calendar.refused", bound + " refused calendar.events: " + r.code() + " " + r.item());
} catch (const std::exception &err) {
unit.fail(q.id, "calendar.unavailable", bound + " cannot be asked: " + err.what());
}
}
static std::atomic<bool> stopping;
int main(int argc, char **argv) {
if (argc == 2 && std::string_view(argv[1]) == "--manifest") {
std::cout << declaration().manifest();
return 0;
}
if (argc != 3 || std::string_view(argv[1]) != "--calendar") {
std::cerr << "agenda: usage: agenda --calendar ${bind.calendar}\n";
return 2;
}
std::signal(SIGTERM, [](int) { stopping = true; });
try {
auto unit = Unit::start(declaration());
// The need's channel: its opening shows the one unit it may address.
auto calendar = yoke::iface::Attachment::attach(argv[2]);
auto bound = bound_unit(*calendar);
unit->health(0, "asks " + bound);
while (!stopping && !unit->done()) {
auto event = unit->next(std::chrono::milliseconds(200));
if (!event)
continue;
if (auto *q = std::get_if<Question>(&*event); q && q->type == "agenda.next")
std::thread([&unit, &calendar, bound, q = *q] { answer(*unit, *calendar, bound, q); }).detach();
}
if (stopping) {
unit->close();
while (unit->next()) {
}
}
} catch (const std::exception &err) {
std::cerr << "agenda: " << err.what() << '\n';
return 1;
}
}
| Part | What it does |
|---|---|
| the attachment | made once, at the start, to the path in --calendar. On a need's channel nothing prevails and nothing yields: the one client always holds control |
| the unit bound | read from the opening: the channel shows that unit and no other, so the first unit record is it |
| the cause | the identifier of the question being answered. A question with no cause starts a chain of its own, and waits 30 s |
| the answer | handed on as it came, here; a real Plugin picks what its own contract says |
| the refusal | translated: the Plugin answers its own asker in its own terms, calendar.refused or calendar.unavailable, and says what it met |
Who asked is in every question, filled by the Core and never by the request: unit:agenda when
agenda asks the calendar, channel:<name> from an interface, operator:<person> from yoke. A Plugin
that gives different things to different askers decides it from that field.
Following a stream
A stream the Plugin uses is followed through the same attachment, and the follow outlives a restart of
the unit it follows: the library starts the stream where it does not flow, subscribes, and subscribes again
each time the delivery ends because the unit's Session did. A stream a need's channel follows is held:
another channel's stop is refused stream.held, naming the unit that follows it; an operator's stop still
stops it.
| Family | Follow | Next frame |
|---|---|---|
| Go | Attachment.Follow(ctx, unit, stream) | Follow.Next(ctx) |
| Rust | Attachment::follow(unit, stream) | Follow::next() |
| Python | await attachment.follow(unit, stream) | await follow.next() |
| C | yoke_follow_stream(a, unit, stream, …) | yoke_follow_next(f, &frame, timeout_ms, &err) |
| C++ | attachment->follow(unit, stream) | follow->next(…) |
A stream followed is declared in uses.<need>.streams and governed by its own capability:
uses:
calendar:
questions: [ calendar.events ]
streams: [ calendar.upcoming ]
capabilities:
- name: stream.calendar.upcoming.follow
governs: { use: { need: calendar, stream: calendar.upcoming } }
When the unit it uses restarts
Its delivery ends and nothing else does. The Plugin is not restarted; a question asked while the other
unit is down is refused unit.not_running or unit.no_session, and the next one is answered once it is
back. A follow carries on by itself.
What the Core keeps of it
Nothing a use carries: not a question's payload, not an answer, not a frame. It reports that a use was
refused, unit.use.refused on the using unit, and that a question was caused by another,
unit.question.chained on the unit asked, with the chain, the asker and the type. A Plugin that carries a
token or a reading for another can count on that.
Next: Handing it on. How an application binds the need and grants the use is a Plugin that uses another; every rule is in the reference, using another unit and a need's channel.