temporal

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0, MIT Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Flows on Temporal (temporal)

Package temporal runs on Temporal the work that requests start: a payment after an approval, an agent that answers a stage, an agent that writes a summary for the approver. Each is a flow, which you write in dandori, one of ritsu's languages, and ritsu makes its Go code. This package starts the flows, and gives the answers of the agents back to the server. Japanese: README.ja.md.

To Read
run work after an approval Start work after an approval
have an agent answer a stage Have an agent check requests
put it on a server you put together in Go Use, below
find a run in Temporal The names in Temporal, below
know how it works, and why the design

A project that ritsu ringi init made with --temporal has code that does all of it (flows.go and cmd/worker). The package is a Go module of its own, github.com/i2y/ringi-server/temporal, so that the framework depends on no SDK.

What it does

A Runner is both the Flows and the Agents of server.Config.

Function What it does
FlowsOf Reads the flows that the request types use from their descriptions (types/<kind>.json): each with its workflow type, its task queue and its outputs
New Makes a Runner of the flows and a client of Temporal
Runner.Run Runs the workers of this process, until its context ends. It returns at once when a worker does not start, and later when one stops on an error it cannot go on from
Runner.CheckWorkers Waits until a worker polls every task queue the flows run on. When its context ends first, it names the queues with none
Runner.Launch Starts a flow after an approval, and tells the server what became of it once it ends. The server calls it
Runner.Ask Starts the flow of an agent, and gives its answer to the server once it ends. The server calls it

A flow is started with the key the server gives as its workflow ID, so a key given again starts nothing. Launch and Ask each start a small workflow of this package, which runs the flow as its child. That of Launch tells Server.WorkEnded what became of the flow (done, with what it ended with, or failed, with why), and the page of the request shows it. That of Ask makes the answer from how the flow ended (ok, doubt, the outputs of a summary, or a failure), and gives it to Server.Answered. Each tells the server from an activity, which Temporal tries again until the server has taken it, so a process that stops in the middle loses nothing.

Use

You need a Temporal server, and the Go code that ritsu made (ritsu gen --target go writes the flows under flows/). Give the runner the flows and the workers this process runs, by their task queues, and give the server the runner. The test TestOneProcess of testdata/examples runs this code:

p, err := server.Load(ticketkinds.Contract, ticketkinds.Lang, ticketkinds.Kinds, os.DirFS(filepath.Join("..", "..", "requests")))
if err != nil {
	t.Fatal(err)
}
listed, err := temporal.FlowsOf(p) // the flows the kinds name, as their descriptions list them
if err != nil {
	t.Fatal(err)
}
flows, err := temporal.New(c, temporal.Config{
	Flows: listed,
	// the workers this process runs, by their task queues: the others run elsewhere
	Workers: map[string]func(client.Client) worker.Worker{
		travel_decision.TaskQueue: func(c client.Client) worker.Worker { return travel_decision.NewWorker(c, nil, travelAgents{}, "") },
		expense_payment.TaskQueue: func(c client.Client) worker.Worker { return expense_payment.NewWorker(c, own, nil, "") },
	},
})
if err != nil {
	t.Fatal(err)
}
srv, err := server.New(server.Config{
	Packages:      []*server.Package{p},
	Store:         memstore.New(),
	Authenticator: servertest.Header{},
	Gate:          server.AllowAll,
	Organization:  orgfiles.New(os.DirFS(filepath.Join("..", "..", "project"))),
	Books:         &servertest.Books{},
	Flows:         flows,
	Agents:        flows,
})
if err != nil {
	t.Fatal(err)
}
if err := srv.ImportOrganization(ctx); err != nil {
	t.Fatal(err)
}
running.Add(2)
go func() { defer running.Done(); srv.Run(ctx) }()
stopped := make(chan error, 1) // why the flows' workers stopped: one did not start, or cannot go on
go func() { defer running.Done(); stopped <- flows.Run(ctx, srv) }()
// Before it serves: a worker polls every task queue the flows run on.
ready, stop := context.WithTimeout(ctx, 30*time.Second)
defer stop()
checked := make(chan error, 1)
go func() { checked <- flows.CheckWorkers(ready) }()
select {
case err := <-stopped:
	t.Fatal(err)
case err := <-checked:
	if err != nil {
		t.Fatal(err)
	}
}
What stands for your own
In the code What it is
p The package ritsu made: the request types (ticketkinds) and their requests directory. Here they are the expense and the contract, which use four flows: precheck_agent, travel_decision, pay and summarize
c A client of Temporal: client.Dial(client.Options{HostPort: "localhost:7233"})
own The tasks of the payment that you write (expense_payment.OwnTasks)
travelAgents{} A Transport of the test, which answers in place of the agents. With nil, the flow calls the agents' providers, with the keys in the environment
memstore.New(), servertest.Header{}, server.AllowAll, servertest.Books{}, the organization's files Parts for tests. Give your own (Parts and packages)
ctx, running, t.Fatal What the test stops the loops with, and how it stops on an error
Which process runs which flow

Workers lists the task queues whose flows this process runs. The flows of the other queues run in other processes, each with the worker of the flow's package and the keys of its agents' providers. Here the other two are the expense's check and the contract's summary: such a process runs expense_precheck.NewWorker(c, nil, nil, "").Run(worker.InterruptCh()), and the same with contract_summary. New refuses a worker of a queue that no flow is on.

Wait for the workers before serving

With no worker on its queue, a flow waits, and so does its request. The code waits for CheckWorkers before it serves (http.ListenAndServe(":8080", srv)), and stops on an error of Run rather than after the 30 seconds. A server watches stopped while it serves, too.

  • CheckWorkers looks at every queue that the runner starts runs on, and that of the workflows of this package (Config.TaskQueue). It asks again after a question to Temporal that fails.
  • Temporal lists a worker for a while after its last poll (about five minutes on the dev server), so a worker that has just stopped counts as one.

The names in Temporal

What Name
a flow launched or asked workflow ID <ticket>/<round>/<serial>, the flow's type and task queue
the workflow that launches a flow workflow ID <ticket>/<round>/<serial>/launch, type requests.launch, task queue requests (Config.TaskQueue)
telling the server what became of it activity requests.ended
the workflow that asks for an answer workflow ID <ticket>/<round>/<serial>/ask, type requests.ask, task queue requests (Config.TaskQueue)
giving the answer to the server activity requests.answer

The tests

cd temporal
go test ./...
go test -race ./...

They start Temporal's dev server themselves, and never download it:

Variable What it names Without it
TEMPORAL_CLI the Temporal CLI the dev server runs from the file the SDK keeps in the system's temporary directory (temporal-cli-go-sdk-<version>). Without that file, the tests that need a server print SKIP
RITSU the ritsu that generates the examples ritsu on PATH. Without one, TestExamples prints SKIP
RINGI_EXAMPLES the examples' project ../examples/project
RINGI_EXAMPLES_GOMOD a go.mod whose requirements (and go.sum) the examples' module takes too: for a machine that builds from its module cache only, one whose versions the cache holds the requirements the generated flows name
Test What it checks
TestFlowsOf, TestFlowsOfVersions The flows read from the descriptions of the examples' kinds (../examples/requests; without them they print SKIP)
TestCheckWorkers Whether a worker polls each queue, as the dev server says, also when the context ends in the middle of a question, or a question fails
TestExamples Generates the expense, the contract and their flows into a temporary module, copies testdata/examples into it, and runs the tests below there
  • TestOneProcess: the code of this document, in a namespace where no other test's workers poll. A day trip goes from its request through the agent's decision to its payment.
  • An agent passes, doubts, fails, and gives an answer of the wrong shape.
  • A contract's summary is attached, and comes too late.
  • A payment is started twice and runs once, and the page of the request says it was done, with its reference.
  • The worker stops between the server's taking an answer and its reply.

The agents answer through a Transport of the test, so nothing goes out to a network. Nothing generated is kept. This is go test -v -run TestExamples .. TestAgentFails takes the longest, as its flow waits 10 and then 20 seconds between its agent's tries.

--- PASS: TestOneProcess (0.33s)
--- PASS: TestSummaryAttached (0.32s)
--- PASS: TestAgentPasses (0.32s)
--- PASS: TestAgentAnswersOutOfShape (0.32s)
--- PASS: TestSummaryLate (0.37s)
--- PASS: TestAgentDoubts (0.37s)
--- PASS: TestPaymentStartsOnce (0.73s)
--- PASS: TestWorkerStopsWhileAnswering (4.34s)
--- PASS: TestAgentFails (30.21s)
ok  	example.test/requests/driver	31.167s
--- PASS: TestExamples (52.32s)

Documentation

Overview

Package temporal runs the flows of the kinds of request on Temporal: the flows a ticket launches, such as a payment once it is approved (server.Flows), and the agents' steps and the notes a stage asks for (server.Agents), whose answers it gives back to the server. The flows are the ones dandori generates for Temporal's Go SDK.

https://i2y.github.io/ringi-server/flows/ and https://i2y.github.io/ringi-server/agent-steps/ say how to use it, and DESIGN.md how it works.

Index

Constants

View Source
const (
	// AskWorkflow is the type of the asking runs: one for each agent's step or note asked.
	AskWorkflow = "requests.ask"
	// AnswerActivity gives an asking run's answer to the server.
	AnswerActivity = "requests.answer"
	// LaunchWorkflow is the type of the launching runs: one for each work a ticket launches.
	LaunchWorkflow = "requests.launch"
	// EndedActivity tells the server what became of a launching run's flow.
	EndedActivity = "requests.ended"
	// DefaultTaskQueue is the task queue of the asking and the launching runs when Config.TaskQueue
	// is "".
	DefaultTaskQueue = "requests"
)

The names this package gives Temporal.

Variables

This section is empty.

Functions

func AskID

func AskID(key server.EffectKey) string

AskID is the workflow ID of the asking run of a key.

func LaunchID

func LaunchID(key server.EffectKey) string

LaunchID is the workflow ID of the launching run of a key.

Types

type Answerer

type Answerer interface {
	Answered(ctx context.Context, key server.EffectKey, a server.Answer) (server.Reply, error)
	WorkEnded(ctx context.Context, key server.EffectKey, e server.WorkEnd) (server.Reply, error)
}

Answerer is where the answers go: *server.Server is one.

type AskResult

type AskResult struct {
	// Outcome is "moved" (the ticket took the answer) or "refused" (the ticket had gone on).
	Outcome string `json:"outcome"`
	// Refused is the kind of the refusal (stale, state), for "refused".
	Refused string `json:"refused,omitempty"`
}

AskResult is what an asking run ends with, once the server has taken its answer.

type Config

type Config struct {
	// Flows are the flows the kinds launch and ask (FlowsOf).
	Flows []Flow
	// Workers are the flows' workers this process runs (Run), by the task queue they poll: each
	// makes a generated package's worker (its NewWorker, with your own tasks and the Transport its
	// agents call out through). A flow whose task queue has none here is run by another process.
	Workers map[string]func(c client.Client) worker.Worker
	// TaskQueue is the task queue of the asking and the launching runs, and of what they tell the
	// server (default DefaultTaskQueue).
	TaskQueue string
	// AnswerTimeout is how long one try at telling the server an answer, or what became of a
	// launched flow, may take (default one minute). A try that takes longer, or whose worker stops,
	// is tried again.
	AnswerTimeout time.Duration
	// WorkerOptions are the options of the worker of the asking and the launching runs.
	WorkerOptions worker.Options
}

Config is what a Runner is made of.

type Flow

type Flow struct {
	// Name is the name the kinds give the flow, which their effects name it by (a flow's `alias` in
	// the kind's description).
	Name string
	// Kind limits the entry to one kind of request, for two kinds that give one name to two flows;
	// "" is every kind.
	Kind string
	// Type and TaskQueue are the flow's workflow type and task queue (`workflow_type` and
	// `task_queue`; the generated package's WorkflowType and TaskQueue).
	Type      string
	TaskQueue string
	// Outputs are the names of a note's outputs in the order its flow declares them (`outputs`):
	// the note is given its outputs in that order (ringi's DESIGN 15). Without them, its outputs
	// keep the order the run ended with them in.
	Outputs []string
}

Flow is a flow the kinds name, and where Temporal runs it. FlowsOf makes them from the kinds' descriptions.

func FlowsOf

func FlowsOf(pkgs ...*server.Package) ([]Flow, error)

FlowsOf answers the flows the kinds of request of the packages run, as the kinds' descriptions list them (types/<kind>.json: `flows`, ringi's DESIGN 12.2): a flow's Name is its `alias`, the name the kinds' effects give it; Type and TaskQueue are its `workflow_type` and `task_queue`; Outputs are the names of its `outputs`, in their order. A name every kind that lists it gives the same flow is one Flow for every kind (Kind ""); a name kinds give different flows is a Flow for each kind. A kind that gives one name two flows, in two of its versions, is an error: a launch and an ask name a flow by the kind and the name only.

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner starts the flows on Temporal for a server: it is the server's Config.Flows and Config.Agents.

func New

func New(c client.Client, cfg Config) (*Runner, error)

New makes a runner that starts the flows with c. It does no I/O.

func (*Runner) Ask

func (r *Runner) Ask(ctx context.Context, a server.Ask) error

Ask starts the asking run of an agent's step or a note, with the workflow ID "<key>/ask": it runs the flow and gives its answer to the server. A key asked before is a success. An error is the framework's to try again.

func (*Runner) CheckWorkers

func (r *Runner) CheckWorkers(ctx context.Context) error

CheckWorkers asks Temporal whether a worker polls each task queue the runner starts runs on: the queues of Config.Flows, and Config.TaskQueue of the asking runs (Run's worker). A run on a queue no worker polls waits until one does, and its ticket with it. It asks about every queue again every 250 milliseconds, also after a question that failed, until Temporal has answered a worker on each, and then answers nil. When ctx ends first, between two questions or in the middle of one, it answers an error that names the queues it has found no worker on, by what Temporal last answered about each: with the error of the last question when that failed, and as not answered when Temporal has answered nothing about the queue. Temporal still lists a worker for some minutes after its last poll, so a worker found may have stopped since. Call it once the workers are up: after Run has started this process's, with the processes that run the others started.

func (*Runner) Launch

func (r *Runner) Launch(ctx context.Context, l server.Launch) error

Launch starts the launching run of a flow a ticket launches, with the workflow ID "<key>/launch": it runs the flow, with the key as its workflow ID, and tells the server what became of it (Server.WorkEnded). A key started before is a success. An error is the framework's to try again.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, to Answerer) error

Run runs the worker of the asking runs, giving their answers to to, and the flows' workers of Config.Workers, until ctx ends or a worker stops on an error it cannot go on from (the error of the asking runs' worker is answered).

func (*Runner) Worker

func (r *Runner) Worker(to Answerer) worker.Worker

Worker makes the worker of the asking runs and the launching runs, on Config.TaskQueue: their answers, and what became of the work launched, go to to. It must run where to can be called, that is in a process of the server.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL