// NewContextFactory returns a ContextFactory capable of creating execution contexts backed
// by the supplied unit's supplied API connection.
func NewContextFactory(
	state *uniter.State,
	unitTag names.UnitTag,
	tracker leadership.Tracker,
	getRelationInfos RelationsFunc,
	storage StorageContextAccessor,
	paths Paths,
	clock clock.Clock,
) (
	ContextFactory, error,
) {
	unit, err := state.Unit(unitTag)
	if err != nil {
		return nil, errors.Trace(err)
	}
	machineTag, err := unit.AssignedMachine()
	if err != nil {
		return nil, errors.Trace(err)
	}
	model, err := state.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}

	zone, err := unit.AvailabilityZone()
	if err != nil {
		return nil, errors.Trace(err)
	}
	f := &contextFactory{
		unit:             unit,
		state:            state,
		tracker:          tracker,
		paths:            paths,
		modelUUID:        model.UUID(),
		envName:          model.Name(),
		machineTag:       machineTag,
		getRelationInfos: getRelationInfos,
		relationCaches:   map[int]*RelationCache{},
		storage:          storage,
		rand:             rand.New(rand.NewSource(time.Now().Unix())),
		clock:            clock,
		zone:             zone,
	}
	return f, nil
}