store

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package store owns the CLI's on-disk layout and the primitives every other package uses to touch it: directory resolution, atomic 0600/0700 writes and a per-profile lock file.

The layout follows PLAN.md "Local data: config, cache, state": config lives in os.UserConfigDir()/teams, the rebuildable cache in os.UserCacheDir()/teams, and user state in a directory we pick ourselves (Go has no os.UserStateDir). Everything except the config file is per profile, because the bot identity and the personal identity must never share a cache or a name resolution.

Index

Constants

View Source
const (
	FileMode fs.FileMode = 0o600
	DirMode  fs.FileMode = 0o700
)

File modes required by PLAN.md: files 0600, directories 0700.

View Source
const (
	// KindTeam marks a team name → team id entry.
	KindTeam = "team"
	// KindChannel marks a (team id, channel name) → channel id entry.
	KindChannel = "channel"
	// KindPerson marks a person key → user id entry.
	KindPerson = "person"
	// KindPersonChat marks a person key → 1:1 chat id entry.
	KindPersonChat = "person_chat"
	// KindEvent marks a short event handle → full event id entry, which is how
	// `teams calendar show <handle>` finds a 152-character Graph event id
	// (plans/calendar.md §4.6).
	KindEvent = "event"
)

Entry kinds reported by ForEach.

View Source
const (
	// NameTTL is how long a team or channel name stays usable. Names change
	// under us - a channel can be renamed or deleted - so they are re-resolved
	// often; `--refresh` bypasses the cache entirely (PLAN.md:170).
	NameTTL = time.Hour

	// PersonTTL is how long a person key → user id or person key → 1:1 chat id
	// mapping stays usable. People and their 1:1 chats change far less often
	// than channel names, so the plan allows a week.
	PersonTTL = 7 * 24 * time.Hour

	// EventTTL is how long an event handle stays resolvable. It matches
	// PersonTTL: a handle is printed to be pasted into a later command, which
	// may be days later, and a stale handle costs one `calendar list`
	// (plans/calendar.md §4.6).
	EventTTL = PersonTTL
)

TTLs from PLAN.md:170: "a TTL of about 1h for names and 7 days for person → user id and person → 1:1 chat id".

View Source
const (
	EnvConfig = "TEAMS_CONFIG"
	EnvCache  = "TEAMS_CACHE_DIR"
	EnvState  = "TEAMS_STATE_DIR"
)

Env variables that relocate the layout. Tests and containers need them (PLAN.md "Local data"); TEAMS_CONFIG is documented in "Profiles".

View Source
const LockTimeout = 2 * time.Second

LockTimeout is how long a read-modify-write waits for the per-profile lock before giving up. It is short on purpose: the lock is advisory and cross-process (a second `teams` invocation, or two commands in one shell script), and a command should fail with a clear message rather than wait behind a process that is stuck.

View Source
const StaleLockAfter = 10 * time.Minute

StaleLockAfter is how old a lock file may be before we assume its owner died.

Variables

View Source
var ErrCorruptAliases = errors.New("alias file is corrupt")

ErrCorruptAliases reports an alias file that could not be parsed. Aliases are user data rather than rebuildable cache, so the loaders return the error next to an empty, usable map, and SetAlias/RemoveAlias refuse to rewrite the file instead of silently dropping what the user configured.

View Source
var ErrCorruptCache = errors.New("entity cache is corrupt or its version is unknown")

ErrCorruptCache reports an entity cache file that could not be used: invalid JSON or an unknown schema version. LoadEntities never fails because of it - the returned cache is empty and usable - and records the error in Problem() so a caller can warn and rebuild (PLAN.md:255: the entity cache is rebuildable data).

Functions

func EnsureDir

func EnsureDir(path string) error

EnsureDir creates a directory tree with 0700 permissions.

func EnsureParent

func EnsureParent(path string) error

EnsureParent creates the parent directory of a file path.

func HumanBytes

func HumanBytes(n int64) string

HumanBytes formats a byte count the way `cache info` prints it.

func LoadAliases

func LoadAliases(path string) (map[string]string, error)

LoadAliases reads the alias file at path, normally Paths.AliasesFile(). A missing or empty file is not an error: it returns an empty, non-nil map and a nil error.

A file that does not parse as a flat TOML name → target table is reported as ErrCorruptAliases, together with that same empty map, so a caller can warn and continue with no aliases. Names are lower-cased on load, because aliases match case-insensitively like every other name (PLAN.md:165).

func LockPath

func LockPath(path string) string

LockPath returns the per-profile lock file that guards path: a ".lock" beside it, created 0600 by Acquire. For Paths.AliasesFile() that is exactly Paths.LockFile(), the lock every per-profile read-modify-write uses (PLAN.md:259). For Paths.EntityCacheFile() it is the cache directory's own .lock, so a cache writer never contends with a state writer.

The lock is advisory and cross-process: it excludes our own processes with an O_EXCL lock file, it cannot stop any other program from writing the same path, and it is not reentrant - a caller that already holds Paths.LockFile() must call LoadAliases/SaveAliases directly rather than SetAlias, which would wait for its own lock.

func PidFromLockFile

func PidFromLockFile(path string) (int, error)

PidFromLockFile reports the pid recorded in a lock file (used by tests).

func ReadFile

func ReadFile(path string) ([]byte, error)

ReadFile reads a file, returning (nil, nil) when it does not exist so callers can treat "not written yet" and "empty" the same way.

func RemoveAlias

func RemoveAlias(path, name string) (bool, error)

RemoveAlias deletes an alias and reports whether it existed. A name that was never set is not an error (a script can remove without checking first), but an invalid name is, because that is a usage mistake rather than a missing alias. Nothing is written when the alias was not there, so removing a missing alias never rewrites the file.

func RemoveIfExists

func RemoveIfExists(path string) error

RemoveIfExists deletes a file, treating a missing file as success.

func RemoveTree

func RemoveTree(path string) error

RemoveTree deletes a directory tree, treating a missing directory as success.

func SaveAliases

func SaveAliases(path string, m map[string]string) error

SaveAliases writes the mapping to path as TOML: atomic, 0600, with parent directories at 0700 (PLAN.md:259). Names are lower-cased and the keys are sorted, so saving the same mapping twice produces byte-identical files and a rewrite shows a one-line diff. A nil map writes an empty file, which LoadAliases reads back as an empty mapping.

func SetAlias

func SetAlias(path, name, target string) error

SetAlias creates or replaces an alias, so re-running it for the same name is how a target is corrected. The name must pass ValidAliasName and the target must not be empty; surrounding whitespace is trimmed from both.

The read-modify-write runs under the per-profile lock (LockPath, short timeout), so two processes cannot lose each other's aliases. A corrupt file is an error rather than something we overwrite, and a caller that already holds the lock must not call this.

func ValidAliasName

func ValidAliasName(name string) bool

ValidAliasName reports whether a name can be used as an alias: letters, digits, dot, dash and underscore, and never empty. Surrounding whitespace is trimmed first, so " boss " is a valid spelling of "boss"; the name is stored lower-cased, because aliases match case-insensitively.

func ValidProfileName

func ValidProfileName(name string) bool

ValidProfileName reports whether a profile name is usable as a path segment. It deliberately rejects anything that could escape the state directory.

func WithLock

func WithLock(ctx context.Context, path string, timeout time.Duration, fn func() error) error

WithLock runs fn while holding the lock at path.

func WriteFile

func WriteFile(path string, data []byte) error

WriteFile atomically writes a 0600 file: the data goes to a temporary file in the same directory which is then renamed over the target, so a crash never leaves a half-written cache or alias file behind.

func WriteFileMode

func WriteFileMode(path string, data []byte, perm fs.FileMode) error

WriteFileMode is WriteFile with an explicit permission bit set.

Types

type Alias

type Alias struct {
	// Name is the name as it is typed (`@boss` on the command line), without the
	// "@", lower-cased like every other name (PLAN.md:165).
	Name string
	// Target is what the name resolves to: a person, a channel path, a team or
	// a raw id, in the same forms the commands accept.
	Target string
}

Alias is one name → target mapping, for `teams alias list` (PLAN.md:168).

func ListAliases

func ListAliases(path string) ([]Alias, error)

ListAliases returns the aliases sorted by name, which is the order `teams alias list` prints and a stable order for tests. The corrupt-file rule is the one from LoadAliases.

type CacheStats

type CacheStats struct {
	// Entries is how many entries are still inside their TTL at the passed
	// instant.
	Entries int
	// Oldest is when the oldest entry still inside its TTL was stored, or the
	// zero time when there is none.
	Oldest time.Time
}

CacheStats summarises a cache for `teams cache info`, which prints an entry count and the age of the entity cache (PLAN.md:260).

type EntityCache

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

EntityCache is the per-profile entity cache: team and channel names → ids, people → user ids and people → 1:1 chat ids (PLAN.md:255, PLAN.md:292).

Every method is safe on a nil *EntityCache and behaves as an empty cache, so a caller that could not load one does not need a special case.

The zero EntityCache is not usable: build one with LoadEntities.

func LoadEntities

func LoadEntities(path string) (*EntityCache, error)

LoadEntities reads the entity cache at path, normally Paths.EntityCacheFile().

A missing file is not an error: it returns an empty cache with a nil error and a nil Problem. A corrupt file (invalid JSON, or a version this build does not know) is not an error either - the cache is rebuildable (PLAN.md:255) - but the fact is recorded in Problem() so the caller can warn, and the cache stays clean so a read-only command does not rewrite the broken file. A real read failure (permissions, an unreadable path) is returned, together with a usable empty cache.

func (*EntityCache) Channel

func (c *EntityCache) Channel(teamID, name string) (string, bool)

Channel returns the channel id cached for a channel of a team, looked up by team id and channel name (PLAN.md:255). Channel names match case-insensitively and whitespace-trimmed, and the team id comes from the team entry or from a URL's groupId.

func (*EntityCache) Clear

func (c *EntityCache) Clear()

Clear drops every entry. It marks the cache dirty only when it actually dropped something, so `teams cache clear` on an already empty cache leaves the file (and its absence) alone.

func (*EntityCache) Dirty

func (c *EntityCache) Dirty() bool

Dirty reports whether anything changed since the last Save, so a read-only command can skip the write (and never rewrite the file on a mere lookup). Put methods, Clear and a Prune that dropped something set it; Save clears it. A nil cache is never dirty.

func (*EntityCache) Event added in v1.1.0

func (c *EntityCache) Event(handle string) (string, bool)

Event returns the full event id cached for a short handle. A handle is lower-case hexadecimal, so the lookup is case-insensitive in practice (plans/calendar.md §4.6).

func (*EntityCache) EventHandles added in v1.1.0

func (c *EntityCache) EventHandles() []string

EventHandles returns every cached handle, which `calendar list` needs to lengthen a handle whose 7-character prefix another event shares (plans/calendar.md §4.6).

func (*EntityCache) ForEach

func (c *EntityCache) ForEach(fn func(key string, entry Entry))

ForEach calls fn for every entry, ordered by kind (teams, channels, people, person chats, events) and then by key, so `cache info` counts and tests see a stable order. It exists because a cache has no meaningful len() of its own, and it reports every stored entry - including ones past their TTL - because it takes no clock.

func (*EntityCache) Person

func (c *EntityCache) Person(key string) (Person, bool)

Person returns the person a key resolved to, where a key is the typed form "@yuki", "yuki" or "yuki@x.com" (PLAN.md:166, PLAN.md:167).

func (*EntityCache) PersonChat

func (c *EntityCache) PersonChat(key string) (string, bool)

PersonChat returns the id of the 1:1 chat with a person. PLAN.md:166 caches the scan that finds it, so the chat scan runs once per person.

func (*EntityCache) PersonUserID

func (c *EntityCache) PersonUserID(key string) (string, bool)

PersonUserID returns the user id cached for a person key.

func (*EntityCache) Problem

func (c *EntityCache) Problem() error

Problem reports why the loaded cache could not be used, or nil when it was loaded (or did not exist) normally. The returned error wraps ErrCorruptCache. A later Save rewrites the file in the current version and clears it.

func (*EntityCache) Prune

func (c *EntityCache) Prune(now time.Time) int

Prune drops the entries whose TTL ran out at now and reports how many went (PLAN.md:170: about an hour for names, 7 days for person → user id and person → 1:1 chat id). now is a parameter, never read from the clock, so the outcome is deterministic and a test can prune at any instant it likes. A prune that dropped something marks the cache dirty, so the file is rewritten without the stale entries.

func (*EntityCache) PutChannel

func (c *EntityCache) PutChannel(teamID, name, id string)

PutChannel stores a (team id, channel name) → channel id mapping. An empty team id, name or id is ignored: a channel name alone is not resolvable (PLAN.md:164), so an entry without a team could never be used.

func (*EntityCache) PutEvent added in v1.1.0

func (c *EntityCache) PutEvent(handle, id string)

PutEvent stores the full event id behind a short handle. An empty handle or id is ignored.

func (*EntityCache) PutPerson

func (c *EntityCache) PutPerson(key string, p Person)

PutPerson stores the person a key resolved to. A person without a user id is not stored, because every caller needs the id to mention or open a chat.

func (*EntityCache) PutPersonChat

func (c *EntityCache) PutPersonChat(key, chatID string)

PutPersonChat stores the 1:1 chat id found for a person key. An empty key or chat id is ignored.

func (*EntityCache) PutTeam

func (c *EntityCache) PutTeam(name, id string)

PutTeam stores a team name → team id mapping, remembering the spelling the user typed (trimmed, but with its original case) so output can echo it. An empty name or id is ignored, because such an entry could only ever produce a bogus hit.

func (*EntityCache) Save

func (c *EntityCache) Save(path string) error

Save writes the cache to path, normally Paths.EntityCacheFile(), as atomic 0600 JSON with parent directories at 0700 (PLAN.md:259). It is a no-op when the cache is not dirty, so the "load, read, save only if dirty" pattern never touches the disk, and a nil cache has nothing to save. On success the recorded Problem is cleared, because the file is now one this build wrote.

func (*EntityCache) SetClock

func (c *EntityCache) SetClock(now func() time.Time)

SetClock replaces the clock that stamps new entries. LoadEntities installs the wall clock; a test injects a fixed one so a TTL assertion does not depend on the machine clock. Passing nil restores the wall clock.

func (*EntityCache) Stats

func (c *EntityCache) Stats(now time.Time) CacheStats

Stats counts the entries that are still inside their TTL at now and reports the age of the oldest of them, which is what `teams cache info` needs (PLAN.md:260). now is a parameter so the command can report a consistent instant.

func (*EntityCache) Team

func (c *EntityCache) Team(name string) (string, bool)

Team returns the team id cached for a team name. Names match case-insensitively and whitespace-trimmed (PLAN.md:165), so "Engineering" and " engineering " are the same entry. Freshness is enforced by Prune, not here, so a lookup never depends on the clock.

type Entry

type Entry struct {
	// Key is the normalized key a lookup uses, not the typed spelling.
	Key string
	// Kind is one of KindTeam, KindChannel, KindPerson, KindPersonChat,
	// KindEvent.
	Kind string
	// Value is the resolved id: a team, channel, user or chat id.
	Value string
	// Name is the spelling the user typed, for output.
	Name string
	// At is when the entry was stored.
	At time.Time
}

Entry is one cached entity as exposed by ForEach. It carries the normalized lookup key, the kind, the resolved id, the spelling the user typed (kept so output can echo it back, PLAN.md:165) and when the entry was stored.

type Location

type Location struct {
	// Kind is one of "config", "secrets", "cache" or "state".
	Kind string
	// Label is the human-readable name shown by `cache info`.
	Label string
	// Path is the file or directory.
	Path string
	// Dir reports whether Path is a directory (its tree is scanned).
	Dir bool
}

Location describes one on-disk artifact for `teams cache info` and for the deletion policy of `teams cache clear`.

type Lock

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

Lock is an advisory, cross-process lock on a file path, implemented with an O_EXCL lock file so it works on every OS without cgo. It guards the per-profile state files (aliases, AI sessions) and mirrors, rather than replaces, the lock MSAL's cache extension takes around the token store.

func Acquire

func Acquire(ctx context.Context, path string, timeout time.Duration) (*Lock, error)

Acquire takes the lock, waiting up to timeout. A zero timeout still tries once. A lock file older than StaleLockAfter is treated as abandoned.

func (*Lock) Path

func (l *Lock) Path() string

Path returns the lock file location.

func (*Lock) Release

func (l *Lock) Release() error

Release removes the lock file. It is safe to call twice.

type Paths

type Paths struct {
	Profile string
	// ConfigDir is the directory holding config.toml.
	ConfigDir string
	// ConfigFile is the TOML config file (shared by every profile).
	ConfigFile string
	// CacheRoot is the parent of CacheDir (os.UserCacheDir()/teams).
	CacheRoot string
	// CacheDir is the rebuildable, per-profile cache directory.
	CacheDir string
	// StateRoot is the parent of StateDir.
	StateRoot string
	// StateDir is the per-profile user-state directory.
	StateDir string
}

Paths is the resolved on-disk layout for one profile.

func Resolve

func Resolve(profile string) (Paths, error)

Resolve returns the layout for a profile. Environment overrides apply to the root directories, so TEAMS_STATE_DIR=/tmp/x still keeps profiles apart.

func (Paths) AIDir

func (p Paths) AIDir() string

AIDir holds session history and memory for this profile.

func (Paths) AIMemoryFile

func (p Paths) AIMemoryFile() string

AIMemoryFile holds the curated, user-visible memory.

func (Paths) AISessionsDir

func (p Paths) AISessionsDir() string

AISessionsDir holds one JSONL file per AI session.

func (Paths) AliasesFile

func (p Paths) AliasesFile() string

AliasesFile holds user-defined aliases (state, not cache).

func (Paths) AuthMetadataFile

func (p Paths) AuthMetadataFile() string

AuthMetadataFile holds our own refresh bookkeeping and the account key. The MSAL blob is opaque and unsupported, so the refresh-token age cannot be read out of it (PLAN.md:92).

func (Paths) EntityCacheFile

func (p Paths) EntityCacheFile() string

EntityCacheFile holds the rebuildable name/person cache.

func (Paths) Locations

func (p Paths) Locations() []Location

Locations lists every path the CLI owns for this profile, in the order `teams cache info` prints them.

func (Paths) LockFile

func (p Paths) LockFile() string

LockFile guards concurrent writers of the per-profile state.

func (Paths) SyncFile

func (p Paths) SyncFile() string

SyncFile is the timestamp file msal-ext watches. It is not a lock: msal-ext puts its own lock at this path plus ".lockfile".

func (Paths) TokenFile

func (p Paths) TokenFile() string

TokenFile is the encrypted MSAL cache. It is a secret: `teams cache clear` never touches it, only `teams auth logout` removes it.

func (Paths) TokenFilePlain

func (p Paths) TokenFilePlain() string

TokenFilePlain is the 0600 plaintext fallback used where no OS keychain is reachable, and the location `token_store = "file"` selects explicitly.

func (Paths) UpdateFile

func (p Paths) UpdateFile() string

UpdateFile is the update check's cache: when it last ran and what the newest release was. It is per profile because every state file is, and it holds nothing sensitive.

type Person

type Person struct {
	// UserID is the Entra object id.
	UserID string
	// DisplayName is the name Teams shows, used by mention rendering.
	DisplayName string
	// Mail is the address membership reported, when it reported one.
	Mail string
}

Person is a resolved person: the shapes PLAN.md:167 needs for `@name` and `--mention`, since a mention needs the user id and mentions carry a display name. Mail is empty when membership did not report one.

type Stats

type Stats struct {
	Path    string
	Exists  bool
	Files   int
	Bytes   int64
	Newest  time.Time
	Oldest  time.Time
	IsDir   bool
	Mode    fs.FileMode
	Problem string
}

Stats describes one file or directory tree for `teams cache info`.

func Scan

func Scan(path string, isDir bool) Stats

Scan measures a path without following symlinks out of the tree. A missing path is not an error: it reports Exists=false so `cache info` can list the locations that have not been created yet.

func (Stats) Age

func (s Stats) Age() time.Duration

Age returns how long ago the newest write happened, or 0 when nothing exists.

Jump to

Keyboard shortcuts

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