Documentation
¶
Overview ¶
Package h2a is a client of harnsy's h2a v1 contract: an outside service holds one WebSocket to a harnsy node, gives tasks to a project's lead or a role, and gets the agents' answers, through disconnects.
The contract is harnsy's (https://harnsy.dev/docs/h2a-v1); this package decides nothing the node decides: it follows the contract's «Client» column on every refusal and close, and passes the node's errors on as they are.
Index ¶
- Constants
- Variables
- type Accepted
- type Address
- type Client
- func (c *Client) Close() error
- func (c *Client) CreateItem(ctx context.Context, to, title, text string) (ItemRef, error)
- func (c *Client) OnState(h func(State))
- func (c *Client) OnWelcome(h func(Welcome))
- func (c *Client) Run(ctx context.Context, h func(ctx context.Context, m Reply) error) error
- func (c *Client) Send(ctx context.Context, m Message) (Accepted, error)
- func (c *Client) Sleep(ctx context.Context, to, mode string) error
- func (c *Client) State(ctx context.Context, project string) (State, error)
- func (c *Client) Wake(ctx context.Context, to string) error
- func (c *Client) Welcome() Welcome
- type Config
- type Counts
- type Cursor
- type Error
- type From
- type HTTPRequest
- type HTTPResponse
- type Inlet
- type ItemRef
- type Limits
- type Message
- type OnHTTPFunc
- type Post
- type ProjectAccess
- type ProjectState
- type Reply
- type State
- type Welcome
Constants ¶
const ( CodeVersion = "h2a_version" CodeHelloRequired = "h2a_hello_required" CodeAuth = "h2a_auth" CodeOff = "h2a_off" CodeReplaced = "h2a_replaced" CodePing = "h2a_ping" CodeRate = "h2a_rate" CodeBadFrame = "h2a_bad_frame" CodeFrame = "h2a_frame" CodePart = "h2a_part" CodeTooBig = "h2a_too_big" CodeAddress = "h2a_address" CodeConversationUnknown = "h2a_conversation_unknown" CodeNoHolder = "h2a_no_holder" CodeDaily = "h2a_daily" CodeForbidden = "h2a_forbidden" CodeNotYours = "h2a_not_yours" CodeNoWake = "h2a_no_wake" CodeSoftStop = "h2a_soft_stop" )
The codes of the contract's §5 (testdata/codes.json, from harnsy).
const ( MoveReconnect = "reconnect" MoveStop = "stop" MoveWait = "wait retry_after" MoveCaller = "caller" MoveWaitUntil = "wait until" )
What a service does (the contract's «Client» column).
const ( PostVacant = "vacant" // nobody holds the post PostStarting = "starting" PostUp = "up" PostPartlyAsleep = "partly_asleep" PostAsleep = "asleep" PostOff = "off" PostArchived = "archived" )
The words of Post.State (harnsy's team-state v1). A word not here is passed on as it is.
const ( RightTalk = "talk" // Send RightRead = "read" // State, OnState RightWake = "wake" // Wake, Sleep RightItems = "items" // CreateItem )
The rights of a pass in a project (welcome.projects[].rights).
const InletBodyMax = 128 << 10
InletBodyMax bounds a request's and an answer's body: a larger request is refused by the node (413), a larger answer is not sent (the node gives the canned one).
const ItemTextBytes = 8000
ItemTextBytes is the contract's limit of an item's text: the text with harnsy's frame around it (§6). The frame's words are the node's, so the SDK refuses here only a text that is over the limit by itself; one under it may still be refused by the node with h2a_too_big.
const Protocol = "harnsy.h2a.v1"
Protocol is the WebSocket subprotocol of the contract.
const SleepAfterStep = "after_step"
SleepAfterStep is the sleep mode: after the holder's turn, the node's default and the only one it keeps (it takes "now" as after_step too).
const Version = "1"
Version is the contract version this SDK speaks.
Variables ¶
var ( // ErrVersion: the node's welcome is not version 1. ErrVersion = errors.New("h2a: the node does not speak h2a version " + Version) // ErrReplaced: another copy of the service signed in with the same pass. ErrReplaced = errors.New("h2a: replaced: another connection of this pass signed in") // ErrClosed: the client was closed. ErrClosed = errors.New("h2a: closed") )
var ErrRunning = errors.New("h2a: Run is already running on this client")
ErrRunning: Run was called while another Run of the client runs.
Functions ¶
This section is empty.
Types ¶
type Address ¶
type Address struct {
Address string `json:"address"`
Name string `json:"name"`
About string `json:"about,omitempty"`
}
Address is one post a pass may write to: «lead» or «role:<id>».
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is one service's connection to the node: Dial signs in, Send gives tasks, Run takes the answers; the connection is kept up by the client, as the contract's «Client» column says.
func Dial ¶
Dial connects and signs in. A refused hello comes back as *Error (its Code says why: CodeAuth, CodeOff, CodeRate…), a welcome of another version as ErrVersion. The client then keeps the connection up until ctx ends, Close is called, or the contract says to stop.
func (*Client) CreateItem ¶ added in v0.2.0
CreateItem raises a new item of the post's role. The node writes its title as its own ([service «…»] and title, one line, 120 characters) and frames text as data from outside. A text over ItemTextBytes is refused here (h2a_too_big), without a frame. Needs "item" in Config.Can.
func (*Client) OnState ¶ added in v0.2.0
OnState sets h to get the node's state events: the posts whose state or counts changed (at most once per 5 s a post), of projects where the pass has read. h runs on one goroutine of the client, one event at a time. The events that come while h runs are coalesced: its next call has each post that changed once, in its newest state; the client never waits on h to read the node. nil: events are dropped. Needs "state" in Config.Can.
func (*Client) OnWelcome ¶ added in v0.3.0
OnWelcome sets h to get the node's welcomes: the current one at once (the first of the connection, before OnWelcome was set), then every welcome after it — one the node sends again on the live connection when the person changes the pass's projects, rights or posts, and the one of each reconnect. h runs on the client's handler goroutine, one call at a time; the welcomes that come while it runs are coalesced to the newest, and the client never waits on h to read the node. nil: welcomes are not handed.
func (*Client) Run ¶
Run hands each agent's reply to h, in seq order, one at a time. h returning nil acknowledges the reply (ack) and saves its seq in the Cursor; an error is returned by Run, and the next Run gets that reply again. A refusal of the connection without a frame's ID comes back as *Error. Run returns when ctx ends, or the client stops for good (the contract's «stop»: *Error with CodeAuth or CodeOff, ErrReplaced). One Run at a time per client (a second gets ErrRunning). Keep h short: while it runs, no new reply is read past the buffer, and a long stall loses the connection (the SDK reconnects and nothing is lost, but it costs time).
func (*Client) Send ¶
Send gives a task or a reply to the node and waits for its Accepted. A disconnect before it is resent with the same ID after the reconnect (the node answers a repeated ID with the same Accepted and delivers it once); h2a_rate is waited out once. A refusal comes back as *Error.
func (*Client) Sleep ¶ added in v0.2.0
Sleep puts to sleep the holder of to that this pass woke last (else h2a_not_yours), after its turn. mode "" is SleepAfterStep (the node's default, not sent). Needs "wake" in Config.Can.
func (*Client) State ¶ added in v0.2.0
State asks the posts and their state of project (its name, as Welcome().Projects has it), or of every project where the pass has read when project is "". Needs "state" in Config.Can.
type Config ¶
type Config struct {
// URL is the gateway's address of the contract: wss://<host>[:port]/h2a/v1.
URL string
// Token is the pass's token (h2a_…): a secret. It goes in the hello
// frame only, never in the URL, a header or a log of this package.
Token string
// Can is what the service takes and sends: "text" (always sent, also
// when not listed), and by need "state" (State, OnState), "wake" (Wake
// and Sleep), "item" (CreateItem). nil: ["text"].
Can []string
// OnHTTP answers the pass's inlets (harnsy 0.11, inlet.go): with it the
// service names "http" and gets each request to an inlet; nil: none.
OnHTTP OnHTTPFunc
// Cursor keeps the last handled seq; nil: MemCursor.
Cursor Cursor
// HTTPClient dials the WebSocket; nil: http.DefaultClient.
HTTPClient *http.Client
// Logf, when set, gets a line on each connect and reconnect (never the
// token).
Logf func(format string, args ...any)
}
Config is how to reach the node and sign in.
type Counts ¶ added in v0.2.0
type Counts struct {
Seats int `json:"seats"`
Working int `json:"working"`
Waiting int `json:"waiting"`
Starting int `json:"starting"`
Idle int `json:"idle"`
Asleep int `json:"asleep"`
Off int `json:"off"`
Vacant int `json:"vacant"`
}
Counts are the role's seats by what they do now.
type Cursor ¶
Cursor keeps the seq of the last reply the service handled, across restarts: the next hello asks for what came after it (resume_after).
func FileCursor ¶
FileCursor is a Cursor in a file: the seq as text, written atomically (a temp file renamed over it). A missing file is 0.
type Error ¶
type Error struct {
Re string // the refused frame's ID, "" for the connection
Code string
Text string // harnsy's words
Field string
RetryAfter time.Duration
Until time.Time
Close int // the WebSocket close code that came with it, 0 none
}
Error is a refusal of the node (contract §5), or the SDK's own refusal of a frame it knows the node would refuse (CodeTooBig).
type HTTPRequest ¶ added in v0.4.0
type HTTPRequest struct {
ID string // the node's id of the request
Inlet int64 // the inlet it came to (Welcome().Inlets)
Method string // GET or POST
Path string // after the inlet's address: "/" or "/<more>"
Query string // the raw query, without "?"
// Headers are the request's headers of the node's list, no other:
// Content-Type, User-Agent, Accept, X-Slack-Signature,
// X-Slack-Request-Timestamp, X-Telegram-Bot-Api-Secret-Token,
// X-Hub-Signature-256. Never a cookie or Authorization.
Headers map[string]string
Remote string // the visitor's address, as the node's gateway judges it
Body []byte // byte for byte: a signature over it checks
}
HTTPRequest is a request to one of the pass's inlets.
type HTTPResponse ¶ added in v0.4.0
HTTPResponse is the service's answer to an HTTPRequest. The node sends it as an inert document: a Content-Type of application/json, text/plain, application/xml or text/xml as it is, any other as a download; no cookie, no redirect. Status 200..599; 0 is 200.
type Inlet ¶ added in v0.4.0
type Inlet struct {
ID int64 `json:"id"`
Name string `json:"name"`
// URL is the inlet's public address; "" while the node is not reached
// from outside (the inlet works only then).
URL string `json:"url"`
}
Inlet is one of the pass's inlets on, as Welcome lists it to a service with Config.OnHTTP: the service may register its URL as a webhook itself.
type Limits ¶
type Limits struct {
FramesPerMinute int `json:"frames_per_minute"`
MessagesPerDay int `json:"messages_per_day"`
TextBytes int `json:"text_bytes"`
FrameBytes int `json:"frame_bytes"`
Queue int `json:"queue"`
QueueHours int `json:"queue_hours"`
PingSeconds int `json:"ping_seconds"`
IdleSeconds int `json:"idle_seconds"`
}
Limits are the node's limits from the welcome (contract §6).
type Message ¶
type Message struct {
// ID is the service's id of the frame; empty: the SDK sets a unique one.
// A repeated ID gets the same Accepted for 24 h and is not delivered twice.
ID string
To string
Conversation string
Text string
}
Message is a task or a reply the service sends. Without Conversation it starts a new conversation to To; with one it writes into it.
type OnHTTPFunc ¶ added in v0.4.0
type OnHTTPFunc func(ctx context.Context, r HTTPRequest) HTTPResponse
OnHTTPFunc is the handler of the pass's inlets (Config.OnHTTP): ctx ends when the client closes. Keep it within the inlet's wait.
type Post ¶ added in v0.2.0
type Post struct {
Address string `json:"address"`
Name string `json:"name"`
State string `json:"state"` // PostVacant, PostStarting, PostUp, …
Counts Counts `json:"counts"`
}
Post is one post (an address) and its state: harnsy's team-state words for the role, word for word. Never a seat, an agent, a session or a node.
type ProjectAccess ¶ added in v0.2.0
type ProjectAccess struct {
Project string `json:"project"`
Rights []string `json:"rights"`
To []Address `json:"to"`
}
ProjectAccess is one project of the pass: its name, the rights the pass has there (RightTalk, RightRead, RightWake, RightItems), and the addresses of its posts (lead:<project id> on a pass of several projects).
type ProjectState ¶ added in v0.2.0
ProjectState is one project's posts.
type State ¶ added in v0.2.0
type State struct {
Projects []ProjectState `json:"projects"`
}
State is the posts of the pass's projects and their state: the answer to a request, or an event (only the posts that changed).
type Welcome ¶
type Welcome struct {
V string `json:"v"`
Project string `json:"project"`
To []Address `json:"to"`
Limits Limits `json:"limits"`
// Projects are every project of the pass with its rights and posts;
// the node sends them only to a service whose Can names "state",
// "wake" or "item".
Projects []ProjectAccess `json:"projects,omitempty"`
// Inlets are the pass's inlets on; the node sends them only to a
// service with Config.OnHTTP (harnsy 0.11).
Inlets []Inlet `json:"inlets,omitempty"`
}
Welcome is the node's answer to a good hello.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
h2a-bot
command
Command h2a-bot gives a task to a harnsy project's lead or role and prints the agents' answers, through disconnects.
|
Command h2a-bot gives a task to a harnsy project's lead or role and prints the agents' answers, through disconnects. |
|
examples
|
|
|
alice-skill
command
Command alice-skill is a skill of Yandex Alice that talks to a harnsy project: «Алиса, попроси Харнси …» — the phrase goes to the project's lead, the skill answers «Принято» at once, and the lead's answer is read out the next time you ask «что ответил Харнси».
|
Command alice-skill is a skill of Yandex Alice that talks to a harnsy project: «Алиса, попроси Харнси …» — the phrase goes to the project's lead, the skill answers «Принято» at once, and the lead's answer is read out the next time you ask «что ответил Харнси». |
|
alice-speaker
command
Command alice-speaker is a skill of Yandex Alice that talks to a harnsy project and reads the agent's answers aloud on your Yandex speaker: a phrase said in the skill goes to the post (the pass's first, or -to), the skill answers «Принято» at once, and when the agent answers, the program asks the speaker over its local protocol (glagol) «попроси Харнси прочитать ответ» — the skill then gives the answer and Alice speaks it.
|
Command alice-speaker is a skill of Yandex Alice that talks to a harnsy project and reads the agent's answers aloud on your Yandex speaker: a phrase said in the skill goes to the post (the pass's first, or -to), the skill answers «Принято» at once, and when the agent answers, the program asks the speaker over its local protocol (glagol) «попроси Харнси прочитать ответ» — the skill then gives the answer and Alice speaks it. |