# Rule-based membership

> Work out who belongs from a rule on users' attributes, so a change of department is the whole move, kept current in both directions.

Instead of adding and removing members by hand, give a set of users a rule, such as "everyone whose `department` is
Finance", and the realm keeps membership current: a user who starts matching joins in the same write, and one who
stops matching leaves. Today the rule lives on a type of your own, not on the shipped `group`.

## Before you begin

- **Privilege:** `RealmOwner`, or a privilege of your own that covers type definitions (`*REALM/entity/type/*`) and
  the objects of your type. See [Who may do what](../../attributes/identity-model/#who-may-do-what).
- **Where:** the API, with your session in `$CVYUH_SESSION` (see [Call the API](../../../develop/api/)).
- **The attribute the rule reads exists** on your user type, such as `department`: see
  [Attributes and validation](../../attributes/attributes-and-validation/).

## How it works

A link can be worked out from a rule instead of made by hand. Give a type of your own a `condition` attribute, and
mark the link's other end, on the user, with `"x-conditional-membership": true`. A `condition` is a filter, written
as for a search (see [Search and paging](../../users/search/)): every user it matches is linked, and every user who stops matching is
unlinked.

The realm keeps it current in both directions, inside the write that caused the change. Change a user's attributes,
and their memberships are worked out again in the same write: when the call returns, they're already in or out.
Change a condition, or create an object with one, and every user it now matches is linked at once, not only on their
next change. Remove the condition, and every link it made is removed.

**How a missing attribute matches.** An attribute the user hasn't set reads as its `default`, if the type gives one.
With no value at all, it matches no condition but `is null`: a user without a `department` is in neither
`department = Finance` nor `department != Finance`. Write `{ "field": "department", "op": "is null" }` to catch them.
Conditions match case exactly: `Finance` and `finance` are different values.

### Who controls membership

A rule hands the choice of members to whoever may write the attributes it reads. If a team may change users'
`department`, that team decides who is in every set whose rule reads `department`, and what those sets give. Base
rules on attributes only your administrators, or your HR load, write, and keep the privileges that change them as
narrow as those that change the set itself.

## Set it up

This makes a `team` type whose members are found by their department.

1. Define the type, with a `condition` and a `members` link to users:

   ```sh
   curl https://foobar.cvyuh.com/api/v0/am/types/v1 \
     -H "Cookie: x-cvyuh-token=$CVYUH_SESSION" \
     -H "Content-Type: application/json" \
     -d '{
       "name": "team", "category": "managed", "cardinality": "collection",
       "description": "A team, its members found by rule",
       "schema": { "type": "object", "properties": {
         "displayName": { "type": "string" },
         "condition":   { "type": "object" },
         "members": { "type": "array",
                      "x-relationship": { "target": "user", "cardinality": "many", "reverse": "teams" } }
       } },
       "policies": { "displayName": ["required"] }
     }'
   ```

   The realm answers `201`.

2. Add the other end, `teams`, to your realm's user type, marked for rule-based membership. Read the type, add this
   under `schema.properties`, and save it back with `PUT` and the revision you read, as
   [Attributes and validation](../../attributes/attributes-and-validation/#set-it-up) describes:

   ```json
   "teams": { "type": "array", "x-conditional-membership": true,
              "x-relationship": { "target": "team", "cardinality": "many", "reverse": "members" } }
   ```

3. Create a team with its rule:

   ```sh
   curl "https://foobar.cvyuh.com/api/v0/am/objects/v1/team?id=finance" \
     -H "Cookie: x-cvyuh-token=$CVYUH_SESSION" \
     -H "Content-Type: application/json" \
     -d '{ "displayName": "Finance",
           "condition": { "field": "department", "op": "=", "value": "Finance" } }'
   ```

   Every user whose `department` is `Finance` is a member at once. Set `department` on Ben, and he joins in the same
   write; change it, and he leaves.

## Limits and defaults

| What | Limit | Past it |
|---|---|---|
| Users a rule is applied to, when the rule is created or changed | 10,000 | The rule is applied to the first 10,000 users it matches, in id order. The others aren't linked, and links the rule made to them before are removed. No error is returned |
| Sets with a rule checked, when a user changes | 10,000 objects of all your rule-bearing types together | Sets past the 10,000th aren't checked for that user: their links to the user stay as they were. No error is returned |
| Where rules work | Links of a type of your own | The shipped `group` can't take a rule yet |

Keep each rule narrow enough to match well under 10,000 users, and keep the number of rule-bearing sets under 10,000.
To check a rule, compare its members (list the link, paged) with a search using the same condition.

## When a change fails

| Answer | Code | What it means | What to do |
|---|---|---|---|
| `400` | `INVALID_REQUEST` | You tried to remove a link the rule made | Change the rule, or the user's attributes |

## Audit record

Saving the type is recorded as `CREATED` or `UPDATED` with its definition. Creating or changing a set with a rule,
and changing the user attributes it reads, are recorded on each object's [change history](../../attributes/identity-model/#every-change-is-recorded),
with who made the change.

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| Some users who match aren't members | The rule matches more than 10,000 users, or the realm has more than 10,000 rule-bearing sets | Split the rule into narrower ones; remove sets you no longer use |
| A user without the attribute isn't in a `!=` set | Missing values match no condition but `is null` | Add an `or` with `is null` |
| A user moved department but kept the old set | The old set's link was made by hand, which takes the rule's place | Remove the hand-made link |

## Good to know

- **The shipped user and group can't use rules on their own links.** `memberOf` and `member` are carried attributes,
  so rule-based membership needs a link of your own, as above. See [What's next for groups](../whats-next/).
- **A rule-made link can't be removed by hand.** Unlinking it is refused, since the next change would make it again.
  Change the rule or the user's attributes instead. A link you make by hand to the same object takes the rule's
  place.
- **The attribute must exist.** Add `department`, or whatever the rule reads, to your user type first.

## Related

- [Custom types](../../attributes/custom-types/): define types of your own.
- [Add groups and members](../add-groups-and-members/): membership you manage by hand.
- [Joiners, movers and leavers](../../lifecycle/joiners-movers-leavers/): a move with rules is one write.
