Skip to content

Connect policy packages

A policy package holds a tenant’s own decisions at a few fixed moments:

  • a punch that could go to more than one place
  • a clock joining, moving or coming back
  • a person enrolled at a clock

Use one when these decisions differ by customer, and you want them made in Connect, tested, rather than in a service of your own.

Connect runs two kinds of package written in Lua. It runs no other Lua.

KindWhat it isWhoseNamed by
Protocol packageHow a device talks: how it is identified, what its messages mean, how commands are built.The install’s.An endpoint’s package.
Policy packageA tenant’s decisions at a short, fixed list of moments, its hooks.The tenant’s own, or a shared one the tenant adopted.An endpoint’s policy.

A hook runs at its moment, never on a schedule. It can only do what the person and device APIs allow. It can set a person’s ids, labels or routes, delete a person, queue commands, start actions and make jobs.

Anything else is for your own system to do. Your system reacts to Connect’s events through the API.

HookCalled whenCalled withReturns
routeA punch has several routes.punch, candidatesOne of the candidates, "pass", or nil.
joinedA device is allowed for the first time (device.joined).deviceWhat to do, or nil.
movedA device’s endpoint was moved to another sync group (device.moved).device, fromWhat to do, or nil.
backA device is heard from after more than its endpoint’s back_after_minutes away (device.back).device, absent_for (seconds)What to do, or nil.
enrolledA person was enrolled at a clock (person.enrolled).person, deviceWhat to do, or nil.

A package is a table of hooks, each a function. A name that is not a hook is refused when the package is loaded.

Here is a short example:

main.lua
return {
joined = function(device)
return { actions = { { action = "get_info" } } }
end,
enrolled = function(person, device)
return { person = { external_ids = { payroll = person.user_id } } }
end,
}

What a hook is given:

ArgumentFields
deviceendpoint and device (its ids within the tenant), id (Connect’s number for it), status, group (its sync group’s id), labels (its endpoint’s labels with its own over them) and info (what its package reported of it: firmware, capabilities).
from (moved){ group = "<the group it was in>" }.
person (enrolled)user_id (their id on the clock), person (Connect’s id for them) and fields (what the clock reported).
punch (route)id (the punch event’s id), endpoint, device, user_id, data (the punch as its package reported it) and labels (the device’s).
candidates (route)The punch’s routes, each { system, tenant, person_id, codes }.

What joined, moved, back and enrolled return is a table of any of these:

KeyDoes
actions{ { action = "clear_users", params = { ... } } }, started on the device as POST .../devices/{endpoint}/{device}/actions starts them (actions).
commands{ { command = "say", params = { ... } } }, queued for the device by name.
jobsJob specs, as POST /api/tenants/{tenant}/jobs takes them, made in the tenant (jobs).
person (enrolled only)Fields written to the person: external_ids, labels, routes, metadata.
delete = true (enrolled only)Deletes the person from the group, and so from the clock.

A hook follows the same rule as an API caller. While the device’s sync group keeps a domain, the group is its only writer (direct writes are refused).

Suppose an action or command writes what the group keeps, such as clear_users on a clock whose group keeps people. It is refused and reported as policy.hook_failed.

  • A hook is recorded with its moment. If the instance that saw the moment stops before it runs the hook, another instance runs it shortly after.
  • A hook runs once in effect. Running a hook again does nothing twice. Each action, command and job it starts is made once for its moment. A person is written the same values. A punch is routed only while it is still undecided.
  • A failure is reported. A hook can fail in four ways. It can raise an error. It can run out of its limits. It can return something it may not. Or it can ask for what cannot be done. Each failure is reported as one policy.hook_failed event. The event holds the hook, the event it was about, the package and version, and the error. Nothing of what failed is done. Whatever else the hook said that could be done is done. The moment’s own event is stored either way.

The route hook can be asked again for the same punch. That happens each time an unrouted punch is worked out again. It happens with hourctl unrouted route, or after a change to the person’s or the group’s routes.

Each failing attempt is reported once, with repeat: true when the attempt before it failed too, so a sink can alert only on the first. Send policy.hook_failed to a sink to alert, open a ticket, or route the punch through the API once the package is fixed.

An endpoint names its policy package in its settings, as it names its protocol package. It uses the name, and it can pin a version prefix:

[[endpoint]]
id = "office"
listener = "web"
path = "/office"
package = "[email protected]"
policy = "clock-lifecycle@1"
back_after_minutes = 4320

The name is looked up in the tenant’s own policy packages first. Then it is looked up in the shared packages the tenant adopted. Naming one the tenant has neither made nor adopted is refused.

If an instance cannot load the package, it still serves the endpoint. It does not call the hooks, and it says so in its log.

Without a policy, no hook is called. A punch with several routes is unrouted. A person enrolled at a clock stays there, unlinked.

Each moment is stored once as an event of the device’s endpoint. It has the same id whichever instance saw it. Then the hook of the same name is called.

The event, and the hook owed for it, are kept in the same transaction as what made the moment. What made the moment can be the device being allowed, blocked or added, its return, or a page of devices of a moved endpoint. So there is never a change without them, or them without the change.

The instance that made the moment runs the hook as soon as the moment is committed. Once what the hook said is done, the hook is no longer owed.

Sometimes that does not happen. The instance may have died between the two steps, or what the hook said could not be written. Then any instance takes the hook up once it is due, 30 seconds after the moment.

Every instance keeps every owed hook on its timers. The instance that owes a hook sends a note about it. Each instance also reads all owed hooks again when it starts, when it may have missed notes, and every 10 seconds. The 10-second read covers a note lost with the instance that owed it. When several instances take a hook up at once, one runs it.

EventWhen
device.joinedThe device was allowed for the first time. That means it was registered as allowed, allowed after waiting, or added as it called in at an endpoint that lets new devices in. A device allowed again after being blocked has not joined again. The event is kept in the same transaction as the allowing.
device.movedIts endpoint was moved to another group. One is sent for each allowed device of the endpoint, with the group it was in. The change is kept with the settings that made it. Any instance tells the devices a page at a time. An instance that stops partway leaves the rest to the next to look. A device is told once. The device joins the new group as a fresh member (members).
device.backIt called in after more than its endpoint’s back_after_minutes since it was last seen. A return is told once, whichever instances the device reaches, and only when the device calls. Nothing watches for absences.

A device’s last-seen time is recorded at most every five minutes. So set back_after_minutes well above that.

A route says where a person’s punches can go. It has three parts:

  • a receiving system (attendance, payroll: names you choose)
  • a tenant in that system
  • the person’s id there (person_id)

A route can also have optional codes for the receiver, such as a cost center or a job. A route has no dates and no “active” flag. It is there or it is not.

{ "system": "attendance", "tenant": "acme", "person_id": "4471", "codes": { "cost_center": "410" } }
  • Default routes are set on a sync group and on an endpoint (routes). They name no person. The person’s id there is their external id for that system, when they have one. An endpoint’s defaults replace its group’s for the same system.
  • A person’s own routes (their routes field) replace the defaults for the same system, and add the rest. A worker placed by two staffing agencies has a route to each, with their id at each.

The routes that are left are the punch’s candidates. They are worked out when the punch is taken in:

Punch taken in from a member clock Candidates own routes over the defaults one none several Goes there marked with its route Unrouted kept aside; punch.unrouted The route hook the endpoint's policy picks one, passes all on, or sets it aside
A punch goes to one place at most. One with no candidates is unrouted only where routing is in use for its endpoint; elsewhere it simply has no route.
CandidatesThe punch
Exactly oneGoes there. Its data says so (data.route), with the person’s id there.
NoneWhere routing is in use for the endpoint, the punch is unrouted. Routing is in use when the endpoint or its group has default routes, or its policy decides routes. Where routing is not in use, the punch simply has no route. It is not set aside, so a route you add later is not given the punches from before it.
SeveralThe endpoint’s route hook decides. It picks one of them, passes all of them on as they are (data.candidates, for a receiver that resolves them itself), or leaves the punch unrouted. Without a policy, the punch is unrouted.

A punch is never copied to several destinations.

An unrouted punch is still stored. It is a fact, and a sink that names no system is sent it. A punch.unrouted event says why: no_route, unknown_person, ambiguous, policy or policy_failed.

The punch is kept aside, whatever its age, until it is routed or its person, group or tenant is deleted. Once routed, it goes out again with the same id, marked with where it goes. If a clock sends it again within the install’s retention_days (default 30), it is not set aside again.

This is on purpose, because a punch is never dropped. Nothing bounds how many unrouted punches there are, except the punches the clocks send. So a group with no routes sets aside every punch of every person until you make routes.

Each is told by a punch.unrouted event. That is the event to alert on. hourctl unrouted list shows them. One hourctl unrouted route works them all out, however many there are, once the routes are made.

Terminal window
hourctl route add --group hq --system attendance --to acme
hourctl route add --person hq/1001 --system attendance --to agency-a --person-id 11 --code work_code=7
hourctl route list --person hq/1001 --for-endpoint town # defaults, own, candidates
hourctl unrouted list hq
hourctl unrouted route hq 0f3c2a9b --system attendance --to agency-b --person-id 22
hourctl unrouted route hq # all of them again; answers in total

An endpoint’s and a group’s routes are part of their settings. A person’s routes are a field of the person. Their unrouted punches are worked out again by themselves when:

  • a person is added, because they may have punched before the group had them. A person can be added through the API, a policy’s enrolled hook, or by enrolling at a clock.
  • a person’s routes or external ids are written.
  • the group’s routes, or those of one of its endpoints, change. This runs in the background, a page of punches at a time, however many there are.

A failure is logged once and leaves the punches unrouted. Work them out again with hourctl unrouted route. Its answer counts how many were routed, passed on and still unrouted, and why.

The routes API is in the sync group reference. The commands are hourctl route and hourctl unrouted.

A sink names the system it speaks for with system. It can also name the tenant in that system with tenant. The sink is sent the punches routed to it, and those passed on with candidates that are all its own. It is sent no others.

Every event about a person carries person_id, their id in that system, when they have one. A sink that names no system is sent every punch, with no person_id.

Terminal window
hourctl -t dealer-north sink add acme-time --receiver attendance \
--receiver-tenant acme --secret-env KEY --event punch --system attendance

Every event also carries Connect’s own ids (tenant, group, person). A receiver can use them to tell whose punch it is.

A person enrolled at a clock becomes an unlinked person of the group. They stay on that clock until an id links them. See people enrolled at a clock.

The endpoint’s enrolled hook decides what happens next. It can:

  • set their external ids, labels, routes or metadata. An external id, or a route that names their id, links them and sends them to every clock their placement picks.
  • delete them from the group, and so from the clock. Do this when onboarding has to go through an HR system first.
  • queue commands, actions and jobs.
  • do nothing, which keeps them unlinked.

Without a hook, your own system can do the same through the API when it receives person.enrolled. A tenant going over its limit on people is told with tenant.limit_reached.

A policy package is a folder with package.toml (kind = "policy"), main.lua and its scenarios in tests/. Build, push and activate it as you would a protocol package, to its tenant:

package.toml
name = "clock-lifecycle"
version = "1.0.0"
kind = "policy"
description = "A clock is set up when it joins and cleared when it moves."
host_api = 2
Terminal window
hourctl pkg test -p packages/policy # its scenarios, offline
hourctl pkg build packages/policy/clock-lifecycle
hourctl -t acme pkg push clock-lifecycle-1.0.0.tar.gz --activate
hourctl -t acme pkg list --policy
hourctl -t acme pkg show clock-lifecycle --policy
hourctl -t acme pkg activate clock-lifecycle@1 --policy # back to revision 1

hourctl pkg push sends a policy bundle to the tenant (--tenant, or the default tenant). It sends a protocol bundle to the install. See hourctl pkg.

The API calls are:

  • GET and POST /api/tenants/{tenant}/packages
  • GET /api/tenants/{tenant}/packages/{name}
  • POST /api/tenants/{tenant}/packages/{name}/revisions/{revision}/activate
  • GET .../revisions/{revision}/bundle

You reach them with a token scoped to the tenant (connect:<tenant>). POST /api/packages refuses a policy package, and the tenant’s route refuses a protocol package.

Every bundle is checked as it is pushed. Its Lua is compiled, its hooks are read and its scenarios are run on the server.

  • A bundle that cannot run is refused and not kept.
  • A bundle whose scenarios fail is kept as a failed revision, with what failed (pkg show lists it). It is never activated.

Revisions are kept per package and activated per line (name and major.minor version). The install’s GET /api/packages lists every tenant’s lines too, each named <tenant>:<name>. Deleting a tenant deletes its packages.

A push has limits. Its scenarios run on a separate thread. They get 1,000,000,000 script steps in all. Each package call has its own work limit besides. A script step is a function call, a return or a loop iteration.

Past the limit, each step still to run stops at once, and the scenarios it was in fail. The push is then kept as a failed revision, saying the scenarios ran out of their work. The limit counts what the scripts did, not how long it took. So a push passes or fails the same on a busy server as on an idle one.

A tenant keeps at most limits.packages lines of its own (50 unless set; see limits). Each line keeps its newest five revisions, and the active one besides. A push of a line past the limit is refused 409.

Activating a revision of a tenant’s own package sends the tenant package.updated. It carries the version the package ran before and the one it runs after.

hourctl promote copies the tenant’s policy packages from one cluster to the same tenant on another. It copies the exact bundles active there. See hourctl promote.

Terminal window
hourctl -t acme promote test production --policy [email protected] --yes

An endpoint promoted brings the policy package line it names. The line is pushed and activated before the endpoint is changed to use it. --all brings every policy package line active for the tenant. hourctl diff lists a policy package line whose active revision differs.

A shared package is a policy package published once for the whole install. You keep it up to date as rules or legislation change. Every tenant that adopts it gets the update.

An instance loads only the shared versions some tenant takes. That means each version a tenant pins, and the newest of each major version a tenant follows. Every other published version is idle there (idle in pkg show --shared). It is kept, and loaded once an adoption or a publish makes a tenant take it.

A version no tenant takes any more is dropped from what the instance runs. So an instance’s start and memory grow with what the tenants use, not with every version ever published.

Publishing is a push, then the scenarios passing on the server, then activation. A published version never changes. Other content under a published version is refused, and a fix is a new version. Only an install token reaches these routes.

Terminal window
hourctl pkg build packages/policy/overtime
hourctl pkg publish --shared overtime-2.4.0.tar.gz
hourctl pkg list --shared
hourctl pkg show overtime --shared

A tenant adopts a shared package by following a major version, or by pinning one version:

Terminal window
hourctl -t acme pkg adopt overtime@2 # each 2.x published reaches acme
hourctl -t beta pkg pin [email protected] # beta keeps 2.3.1
hourctl -t acme pkg adopted
hourctl -t acme pkg drop overtime
Published for the install overtime 2.3.1 overtime 2.4.0 overtime 3.0.0 idle: no tenant takes it pinned followed: newest 2.x Tenant beta pin [email protected] Tenant acme adopt overtime@2
Publishing 2.5.0 moves acme to it at once and sends acme package.updated; beta stays on 2.3.1.
AdoptedRuns
overtime@2 (follows)The newest 2.x published, from the moment it is published.
[email protected] (pins)2.3.1, whatever is published after it.

The tenant’s endpoints then name it as their policy, as they name the tenant’s own: policy = "overtime@2" (or "overtime"). The version the adoption takes must match what the endpoint asks for. For example, an endpoint asking for overtime@3 of a tenant that follows overtime@2 is refused. A tenant’s own package of the same name comes first.

  • Updates reach followers with no other step. Each tenant that moves to another version gets package.updated, with the version before and the one it runs after. So does a tenant whose adoption is made or changed. The event is recorded with the change, and sent only if the change is kept. It goes out under the tenant’s source connect. A tenant’s sink gets it by naming connect in its sources. Install-level sinks get every tenant’s. A tenant that pins gets nothing. A publish whose scenarios fail changes no tenant.
  • Only what tenants use is loaded. A published version no tenant takes is idle (pkg show --shared). It is kept, and loaded once a tenant takes it.
  • Adoptions are checked. A tenant can adopt only a published version. Dropping an adoption is refused while an endpoint of the tenant names it. A tenant adopts only shared packages, and never sees another tenant’s own.

hourctl promote copies shared packages and adoptions between clusters:

Terminal window
hourctl promote test production --shared [email protected] --yes
hourctl -t acme promote test production --adoption overtime --yes

A version goes as the exact bundle published on the first cluster. The plan is refused when the target has that version published with other content. An adoption brings the version it takes. An endpoint whose policy is an adopted shared package brings the adoption.

--all brings every published version and every adoption of the tenant. hourctl diff lists a shared version whose content differs, and an adoption that differs.

The API for shared packages is (install tokens only):

  • GET and POST /api/packages/shared
  • GET /api/packages/shared/{name}
  • POST /api/packages/shared/{name}/revisions/{revision}/activate
  • GET .../revisions/{revision}/bundle

The API for adoptions is:

  • GET /api/tenants/{tenant}/packages/adopted
  • PUT and DELETE /api/tenants/{tenant}/packages/adopted/{name}, with {"version": "2"} to follow or {"version": "2.3.1"} to pin

A tenant’s adoptions are shown with the tenant (adopted in GET /api/tenants/{tenant}). You can’t name a protocol package shared, and you can’t name a policy package adopted. Those names are routes.

Time and Attendance has shared policy packages of its own, adopted the same way. See policies.

A policy package’s scenarios call its hooks with what Connect would hand them, and check what they decide. hourctl pkg test runs them. A hook without a test fails the run.

tests/work-code.toml
description = "The work code entered at the clock picks the agency"
[[step]]
name = "work code 7 is agency A's"
hook = "route"
punch = { id = "p1", endpoint = "town", device = "T1", user_id = "1001", data = { work_code = "7" } }
candidates = [
{ system = "attendance", tenant = "agency-a", person_id = "11", codes = { work_code = "7" } },
{ system = "attendance", tenant = "agency-b", person_id = "22", codes = { work_code = "8" } },
]
[step.expect]
route = 1 # the first candidate; "pass"; or "unrouted"
[[step]]
hook = "moved"
device = { endpoint = "office", device = "C1", group = "plant-7" }
from = { group = "hq" }
[step.expect]
effects = { actions = [{ action = "get_info" }] } # what it returned, as a subset; {} for nothing

error_contains expects the hook to fail with that text. What a hook returns is checked as strictly as Connect checks it at run time. So a scenario fails on a job spec that POST .../jobs would refuse, wrong parameters for a standard action, or a person field that does not exist. A package’s own actions (x_...) are checked by the device’s protocol package, not here.

Every hook has a tested recipe. A recipe is a policy package with its scenarios and a page saying what it does and why. See all recipes. They are in the example packages repository under policy/, and hourctl pkg test runs their scenarios.

RecipeHookWhat it does
route-by-work-coderouteA worker placed by several staffing agencies enters a work code at the clock. The route whose codes.work_code matches takes the punch. With no code, or a code no route has, the punch is unrouted, to route by hand.
multi-agency-clockrouteClocks at a client’s sites serve several agencies’ workers. The route whose codes.site is the clock’s site label takes the punch. If two routes are at one site, the work code picks. Anything else is unrouted.
clock-lifecyclejoined, backA clock put into service has its information read. It is read again when the clock is back after more than a week away. It never clears punches, because the clock may still hold some that have not reached Connect. The people of a clock moved to another site are the new group’s to write.
repaired-clockback (actions, jobs)A ZK clock on push 2.4 or 3.4 that is back after days away (a repair) has its information read. Every punch it holds is read again overnight, as a job in the bulk lane. When a clock is back from a short outage, nothing is done.
link-by-pinenrolledPeople are enrolled under their payroll number. The PIN becomes their payroll id, which links them and sends them to every clock.
onboard-firstenrolledOnboarding goes through HR first. Someone enrolled at an ordinary clock is deleted. Someone enrolled at a supervisor’s clock (role = "supervisor") is kept unlinked until HR links them.
enroll-for-the-agencyenrolled (routes, labels, metadata)Someone enrolled at an agency’s clock (agency label) is routed to the agency’s tenant under their worker number. They are labelled with the clock’s site, and noted with the clock that enrolled them.

A hook names commands as it names actions. But a command belongs to one protocol package, so a recipe that uses one works for one make of clock only. You can publish any recipe as a shared package (hourctl pkg publish --shared) and adopt it.