seed

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 19 Imported by: 0 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.

Documentation

Overview

Package seed implements the test-tenant seeding harness for chunk 0.3: it fills a Microsoft 365 test tenant with known, recognisably-prefixed data across the v1 workloads (Exchange mail, calendar, contacts; OneDrive; SharePoint document libraries and lists) and records exactly what it created in a seed manifest that later chunks assert against.

This package is a library in the sense that it takes all configuration as explicit arguments and never reads the environment itself (see config.go); the one exception is test setup code in _test.go files, which follows the same pattern already used by internal/tester/tconfig for integration-test credentials. Only src/cmd/seed (a program, not library code) reads the process environment and builds a Config from it.

Index

Constants

View Source
const (
	// EnvTenantID, EnvClientID and EnvClientSecret are the application's
	// credentials for the test tenant. These match the fork's CLAUDE.md.
	EnvTenantID     = "AZURE_TENANT_ID"
	EnvClientID     = "AZURE_CLIENT_ID"
	EnvClientSecret = "AZURE_CLIENT_SECRET"

	// EnvSeedUserID names an existing, already-licensed Microsoft 365 user
	// (UPN or object ID) whose mailbox and OneDrive the seeder writes
	// dedicated, Prefix-named folders into. The harness never creates this
	// user: it must already exist in the test tenant.
	EnvSeedUserID = "SEED_USER_ID"

	// EnvSeedSiteID names an existing SharePoint site (canonical Graph site
	// ID, e.g. "contoso.sharepoint.com,<site-guid>,<web-guid>") that the
	// seeder adds a dedicated, Prefix-named document library and list to.
	// The harness never creates this site: it must already exist.
	EnvSeedSiteID = "SEED_SITE_ID"

	// EnvManifestPath overrides where the seeder writes the seed manifest.
	// See manifest.go for the schema. Defaults to DefaultManifestPath.
	EnvManifestPath = "SEED_MANIFEST_PATH"
)

Environment variable names the harness (src/cmd/seed and its integration test) requires. Centralised here, as plain string constants, so the seeder, the integration smoke test, the nightly workflow and docs all agree on one set of names. Defining the names here does not violate the "library never reads env vars" rule: no os.Getenv call lives in this package outside of _test.go files.

View Source
const DefaultManifestPath = "seed-manifest.json"

DefaultManifestPath is used when EnvManifestPath is unset. It is relative to the process's working directory, which by convention is the corso repository root (see docs/test-tenant-harness.md for the exact invocation).

View Source
const ManifestSchemaVersion = 3

ManifestSchemaVersion is bumped whenever the shape of Manifest or ManifestItem changes incompatibly. Consumers (0.7's library API tests, 3.5's k3ep tests) should check it before relying on new fields.

Version history:

  • 1: initial schema (chunk 0.3, first round). CreatedAt/ModifiedAt existed as plain time.Time but were not actually populated by five of six workloads, and disagreed between a found and a created item for the sixth - see version 2.
  • 2: CreatedAt/ModifiedAt changed from time.Time to *time.Time, and are now genuinely populated, from the same real Graph createdDateTime/lastModifiedDateTime, identically whether the item was found already existing or just created. A consumer checking for schema version 1 and reading these two fields as non-pointer time.Time will fail to compile/unmarshal against a version-2 manifest; a consumer written against version 2 must treat a missing/null CreatedAt or ModifiedAt as "Graph has no date for this item's kind" (see the field's own doc comment for exactly which three container kinds that applies to), not as an error.
  • 3: added ManifestItem.Recurrence (nil except on the one recurring calendar event, Kind "event_recurring") and a new Kind, "event_exception", for that series' one exception occurrence as its own top-level item. Purely additive - every field from version 2 keeps its meaning, and a consumer that ignores unknown JSON fields and never asks for Kind "event_recurring"/"event_exception" is unaffected - but bumped anyway per this constant's own rule, since a consumer that *does* want to assert against a recurring series needs to know this version is the first one where that's possible.
View Source
const Prefix = "k3ep-seed"

Prefix identifies every object this package creates. It must appear in every container and item name so a human auditing the tenant can find and, if ever necessary, remove everything the harness owns by hand.

Variables

RequiredEnvVars are the env vars that must be set (to a non-empty value) before the seeder, or its integration test, can run. Credential validation (Done-when #7 of this chunk) checks every name in this list.

Functions

func AlreadyExists

func AlreadyExists(err error) bool

AlreadyExists reports whether err is Graph's "an item with this name already exists in this container" conflict, as returned by api.Drives().PostItemInContainer with control.Skip. The seeder treats this the same as ContainerNotFound would have reported "found": it means two processes (or two runs) raced to create the same item, and whichever one lost should go look the item up rather than fail.

func ContainerNotFound

func ContainerNotFound(err error) bool

ContainerNotFound reports whether err is the "no container matched that name" outcome of the fork's Mail/Contacts/Events GetContainerByName calls, as opposed to a genuine request failure that a seeding attempt should not paper over by trying to create a duplicate.

Those three GetContainerByName implementations (pkg/services/m365/api/{mail,contacts,events}.go) return a filtered, zero-result list as a plain clues error with the message "container not found" - not wrapped in the exported core.ErrNotFound sentinel, because the underlying Graph call itself succeeded (200 OK, empty list). A real Graph-level 404 (e.g. a stale container ID) *is* wrapped in core.ErrNotFound by the graph package, so this helper checks both.

func FindOrCreate

func FindOrCreate[T any](
	find func() (item T, found bool, err error),
	create func() (item T, err error),
) (T, bool, error)

FindOrCreate is the seeder's idempotency primitive. find looks for an item that already satisfies the seed definition (typically: same name, same parent); if found, that exact item is reused untouched. Only when find reports nothing does create run. Calling FindOrCreate twice in a row, with a find that can see what the first call's create produced, is guaranteed to create nothing the second time - that guarantee is this package's entire repeatability story, and is exercised directly in upsert_test.go without touching Graph.

func MissingVars

func MissingVars(get func(string) string, names []string) []string

MissingVars reports the names, in RequiredEnvVars order, of every env var in names whose value (as returned by get) is empty. It never receives or returns a value, only names: the caller passes a lookup function so this stays a pure, testable check with no direct access to the process environment, and so that whatever calls it can log the result without risk of accidentally logging a secret.

func MissingVarsError

func MissingVarsError(missing []string) error

MissingVarsError formats the result of MissingVars into the clear, name-only message the harness reports on start-up (Done-when #7): it never includes a value, only the variable names that are missing.

Types

type Config

type Config struct {
	TenantID     string
	ClientID     string
	ClientSecret string
	UserID       string
	SiteID       string
	ManifestPath string
}

Config carries everything the seeder needs, gathered by the caller (src/cmd/seed/main.go, or a test's setup code) from the environment. Nothing in this package reads these values from anywhere else.

type Manifest

type Manifest struct {
	SchemaVersion int            `json:"schema_version"`
	GeneratedAt   time.Time      `json:"generated_at"`
	TenantID      string         `json:"tenant_id"`
	Prefix        string         `json:"prefix"`
	Items         []ManifestItem `json:"items"`
}

Manifest is the machine-readable record of everything the seeder put in the test tenant. The seeder writes one every run (see Write); 0.7 and 3.5 read it back (see Load) to check that listing the tenant matches what was seeded.

func LoadManifest

func LoadManifest(path string) (Manifest, error)

LoadManifest reads back a manifest previously written by Write. Later chunks (0.7, 3.5) use this to compare what they observe in the tenant against what the seeder recorded.

func NewManifest

func NewManifest(tenantID string, items []ManifestItem) Manifest

NewManifest builds a Manifest from the items the seeder collected, stamping GeneratedAt with now and sorting Items for determinism.

func Run

func Run(ctx context.Context, c api.Client, cfg Config, report func(string)) (Manifest, error)

Run seeds every v1 workload (Exchange mail, calendar, contacts; OneDrive; SharePoint document library and list) into the tenant identified by c and cfg, idempotently, then writes the resulting manifest to cfg.ManifestPath and returns it.

Run never deletes anything. Each workload's seed* function finds-or- creates its own dedicated, Prefix-named containers and items; calling Run again leaves everything an earlier run created exactly as it was.

report, if non-nil, receives one line at a time: the resolved target user and site (name/UPN and ID, never a credential) before any write, and a found-versus-created tally per workload afterwards. Like every other long-running operation in this fork, Run itself never writes to stdout or a log file - the caller decides where these lines go. src/cmd/seed prints them; the integration test writes them to the test log via t.Log.

func (Manifest) ItemsByWorkload

func (m Manifest) ItemsByWorkload(w Workload) []ManifestItem

ItemsByWorkload returns only the items belonging to the given workload, in the manifest's stored (deterministic) order.

func (Manifest) Write

func (m Manifest) Write(path string) error

Write serialises the manifest as indented JSON to path, creating any missing parent directories. It never writes a credential: Manifest and ManifestItem have no field capable of holding one.

type ManifestItem

type ManifestItem struct {
	// Workload is the v1 workload this item belongs to.
	Workload Workload `json:"workload"`

	// Kind distinguishes items within a workload, e.g. "folder" vs
	// "message", or "library" vs "list_item". Free text, but stable once
	// used: later chunks may filter on it.
	Kind string `json:"kind"`

	// ID is the item's Microsoft Graph ID. Stable across seeder runs: the
	// seeder looks up an existing item by name before creating a new one, so
	// re-running never changes a previously-recorded ID.
	ID string `json:"id"`

	// Name is the item's display name or subject - whatever Graph property
	// the seeder matched on to decide "this already exists".
	Name string `json:"name"`

	// FolderPath is the sequence of container display names from the root
	// of the owning mailbox/drive down to (and including) this item's
	// immediate parent, joined with "/". Empty for top-level containers.
	FolderPath string `json:"folder_path,omitempty"`

	// SizeBytes is the content size for items that have one (OneDrive
	// files, mail attachments). Zero/omitted for items with no size.
	SizeBytes int64 `json:"size_bytes,omitempty"`

	// CreatedAt and ModifiedAt come straight from Graph's own
	// createdDateTime/lastModifiedDateTime, read off the same object
	// regardless of whether that object was found already existing or
	// just created - see each seed*() function's FindOrCreate call, which
	// returns the full Graph object on both paths for exactly this reason.
	//
	// Three container kinds have no date at all because Graph itself does
	// not return one for them: a mail folder (Kind "folder" under
	// WorkloadExchangeMail), a calendar (Kind "calendar" under
	// WorkloadExchangeCalendar) and a contacts folder (Kind "folder" under
	// WorkloadExchangeContacts) all model as a bare Graph Entity, not the
	// OutlookItem/BaseItem that carries createdDateTime/lastModifiedDateTime.
	// Every other item in this manifest - messages, events, contacts,
	// OneDrive folders and files, the SharePoint library and its files,
	// the SharePoint list and its items - does carry one.
	//
	// These are pointers, not plain time.Time, specifically so the three
	// dateless container kinds can be nil and genuinely omitted from the
	// JSON: encoding/json's "omitempty" never treats a zero-valued struct
	// (which time.Time is) as empty, only nil/zero-length/zero-number
	// values, so a plain time.Time field would always serialise even when
	// there is no real date to report.
	CreatedAt  *time.Time `json:"created_at,omitempty"`
	ModifiedAt *time.Time `json:"modified_at,omitempty"`

	// ResourceID is the ID of the mailbox, drive or site that owns this
	// item - i.e. Config.UserID, the OneDrive drive ID, or Config.SiteID.
	ResourceID string `json:"resource_id"`

	// Recurrence is non-nil only for the one recurring calendar event
	// this package seeds (Workload WorkloadExchangeCalendar, Kind
	// "event_recurring"). See RecurrenceDetail.
	Recurrence *RecurrenceDetail `json:"recurrence,omitempty"`
}

ManifestItem describes exactly one thing the seeder created or found already present (because a previous run created it) in the test tenant. Every field a later chunk's assertion might need is here: a stable ID, a human name, where it lives, and when/how big it is.

type RecurrenceDetail

type RecurrenceDetail struct {
	// CancelledOccurrenceIDs are this series'
	// Eventable.GetCancelledOccurrences() entries exactly as Graph returns
	// them (format "<seriesId>.<occurrenceStartDateTime>"). A later chunk
	// listing this calendar should find none of these IDs as a visible
	// event - that is what "cancelled" means. Always length 1 for this
	// seeded series (one deliberately cancelled occurrence), but a slice
	// because that is Graph's actual shape for the field.
	CancelledOccurrenceIDs []string `json:"cancelled_occurrence_ids"`

	// ExceptionOccurrenceIDs are the Graph IDs of this series'
	// Eventable.GetExceptionOccurrences() entries. Each one is also
	// present as its own ManifestItem (Kind "event_exception") elsewhere
	// in Manifest.Items, with its own Name/CreatedAt/ModifiedAt, so it can
	// be asserted against directly like any other item - this field is
	// just the index pointing at it. Always length 1 for this seeded
	// series, for the same reason as CancelledOccurrenceIDs.
	ExceptionOccurrenceIDs []string `json:"exception_occurrence_ids"`
}

RecurrenceDetail records what a later chunk needs in order to assert "listing a seeded mailbox matches the seed manifest" against a recurring series, not just its series master: which occurrence Graph no longer returns at all (cancelled), and which occurrence Graph returns with different content (an exception). Both fields are read through the typed Eventable.GetCancelledOccurrences()/ GetExceptionOccurrences() fields the Graph SDK v1.104.0 upgrade (chunk 0.5) promoted out of AdditionalData - this manifest entry is the thing that actually exercises that migration against real Graph data, since every other seeded event is a single non-recurring occurrence.

type Workload

type Workload string

Workload names the v1 workload a manifest item belongs to. These strings are the contract later chunks assert against; don't rename a value once anything depends on it (add a new one instead, and bump ManifestSchemaVersion if the meaning of an existing one changes).

const (
	WorkloadExchangeMail      Workload = "exchange-mail"
	WorkloadExchangeCalendar  Workload = "exchange-calendar"
	WorkloadExchangeContacts  Workload = "exchange-contacts"
	WorkloadOneDrive          Workload = "onedrive"
	WorkloadSharePointLibrary Workload = "sharepoint-library"
	WorkloadSharePointList    Workload = "sharepoint-list"
)

type WorkloadSummary

type WorkloadSummary struct {
	Workload Workload
	Found    int
	Created  int
}

WorkloadSummary tallies, for one workload, how many items the seeder found already present versus how many it had to create. This is the "found versus created" accounting a human re-running the seeder or the smoke test can check against a reported result, without this package ever logging an item's name, subject, filename or any credential - counts and workload names only.

func (WorkloadSummary) String

func (s WorkloadSummary) String() string

Jump to

Keyboard shortcuts

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