Skip to content

Commit

Permalink
add Context.Reference - a Tag with a default value
Browse files Browse the repository at this point in the history
  • Loading branch information
tim-smart committed Nov 19, 2024
1 parent 6560e2d commit 82e2ac0
Show file tree
Hide file tree
Showing 5 changed files with 133 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/funny-dolphins-joke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": minor
---

add Context.Reference - a Tag with a default value
69 changes: 69 additions & 0 deletions packages/effect/src/Context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,38 @@ export interface Tag<in out Id, in out Value> extends Pipeable, Inspectable {
[Unify.ignoreSymbol]?: TagUnifyIgnore
}

const ReferenceTypeId: unique symbol = internal.ReferenceTypeId

/**
* @since 3.11.0
* @category symbol
*/
export type ReferenceTypeId = typeof ReferenceTypeId

/**
* @since 3.11.0
* @category models
*/
export interface Reference<in out Id, in out Value> extends Pipeable, Inspectable {
readonly [ReferenceTypeId]: ReferenceTypeId
readonly defaultValue: () => Value

readonly _op: "Tag"
readonly Service: Value
readonly Identifier: Id
readonly [TagTypeId]: {
readonly _Service: Types.Invariant<Value>
readonly _Identifier: Types.Invariant<Id>
}
of(self: Value): Value
context(self: Value): Context<Id>
readonly stack?: string | undefined
readonly key: string
[Unify.typeSymbol]?: unknown
[Unify.unifySymbol]?: TagUnify<this>
[Unify.ignoreSymbol]?: TagUnifyIgnore
}

/**
* @since 2.0.0
* @category models
Expand All @@ -63,6 +95,14 @@ export interface TagClass<Self, Id, Type> extends Tag<Self, Type> {
new(_: never): TagClassShape<Id, Type>
}

/**
* @since 3.11.0
* @category models
*/
export interface ReferenceClass<Self, Id, Type> extends Reference<Self, Type> {
new(_: never): TagClassShape<Id, Type>
}

/**
* @category models
* @since 2.0.0
Expand Down Expand Up @@ -172,6 +212,15 @@ export const isContext: (input: unknown) => input is Context<never> = internal.i
*/
export const isTag: (input: unknown) => input is Tag<any, any> = internal.isTag

/**
* Checks if the provided argument is a `Reference`.
*
* @param input - The value to be checked if it is a `Reference`.
* @since 3.11.0
* @category guards
*/
export const isReference: (u: unknown) => u is Reference<any, any> = internal.isReference

/**
* Returns an empty `Context`.
*
Expand Down Expand Up @@ -259,7 +308,9 @@ export const add: {
* @category getters
*/
export const get: {
<I, S>(tag: Reference<I, S>): <Services>(self: Context<Services>) => S
<Services, T extends ValidTagsById<Services>>(tag: T): (self: Context<Services>) => Tag.Service<T>
<Services, I, S>(self: Context<Services>, tag: Reference<I, S>): S
<Services, T extends ValidTagsById<Services>>(self: Context<Services>, tag: T): Tag.Service<T>
} = internal.get

Expand Down Expand Up @@ -407,3 +458,21 @@ export const omit: <Services, S extends Array<ValidTagsById<Services>>>(
* @category constructors
*/
export const Tag: <const Id extends string>(id: Id) => <Self, Shape>() => TagClass<Self, Id, Shape> = internal.Tag

/**
* @example
* import { Context, Layer } from "effect"
*
* class MyTag extends Context.Reference<MyTag>()("MyTag", {
* defaultValue: () => ({ myNum: 108 })
* }) {
* static Live = Layer.succeed(this, { myNum: 108 })
* }
*
* @since 3.11.0
* @category constructors
*/
export const Reference: <Self>() => <const Id extends string, Service>(
id: Id,
options: { readonly defaultValue: () => Service }
) => ReferenceClass<Self, Id, Service> = internal.Reference
3 changes: 3 additions & 0 deletions packages/effect/src/Effect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,9 @@ declare module "./Context.js" {
interface Tag<Id, Value> extends Effect<Value, never, Id> {
[Symbol.iterator](): EffectGenerator<Tag<Id, Value>>
}
interface Reference<Id, Value> extends Effect<Value> {
[Symbol.iterator](): EffectGenerator<Reference<Id, Value>>
}
interface TagUnifyIgnore {
Effect?: true
Either?: true
Expand Down
2 changes: 2 additions & 0 deletions packages/effect/src/STM.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ export interface STMTypeLambda extends TypeLambda {
*/
declare module "./Context.js" {
interface Tag<Id, Value> extends STM<Value, never, Id> {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface Reference<Id, Value> extends STM<Value> {}
}

/**
Expand Down
58 changes: 54 additions & 4 deletions packages/effect/src/internal/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type * as C from "../Context.js"
import * as Equal from "../Equal.js"
import type { LazyArg } from "../Function.js"
import { dual } from "../Function.js"
import { globalValue } from "../GlobalValue.js"
import * as Hash from "../Hash.js"
import { format, NodeInspectSymbol, toJSON } from "../Inspectable.js"
import type * as O from "../Option.js"
Expand All @@ -14,6 +15,9 @@ import * as option from "./option.js"
/** @internal */
export const TagTypeId: C.TagTypeId = Symbol.for("effect/Context/Tag") as C.TagTypeId

/** @internal */
export const ReferenceTypeId: C.ReferenceTypeId = Symbol.for("effect/Context/Reference") as C.ReferenceTypeId

/** @internal */
const STMSymbolKey = "effect/STM"

Expand Down Expand Up @@ -54,6 +58,10 @@ export const TagProto: any = {
return make(this, self)
}
}
export const ReferenceProto: any = {
...TagProto,
[ReferenceTypeId]: ReferenceTypeId
}

/** @internal */
export const makeGenericTag = <Identifier, Service = Identifier>(key: string): C.Tag<Identifier, Service> => {
Expand Down Expand Up @@ -89,6 +97,28 @@ export const Tag = <const Id extends string>(id: Id) => <Self, Shape>(): C.TagCl
return TagClass as any
}

/** @internal */
export const Reference = <Self>() =>
<const Id extends string, Service>(id: Id, options: {
readonly defaultValue: () => Service
}): C.ReferenceClass<Self, Id, Service> => {
const limit = Error.stackTraceLimit
Error.stackTraceLimit = 2
const creationError = new Error()
Error.stackTraceLimit = limit

function ReferenceClass() {}
Object.setPrototypeOf(ReferenceClass, ReferenceProto)
ReferenceClass.key = id
ReferenceClass.defaultValue = options.defaultValue
Object.defineProperty(ReferenceClass, "stack", {
get() {
return creationError.stack
}
})
return ReferenceClass as any
}

/** @internal */
export const TypeId: C.TypeId = Symbol.for("effect/Context") as C.TypeId

Expand Down Expand Up @@ -162,6 +192,9 @@ export const isContext = (u: unknown): u is C.Context<never> => hasProperty(u, T
/** @internal */
export const isTag = (u: unknown): u is C.Tag<any, any> => hasProperty(u, TagTypeId)

/** @internal */
export const isReference = (u: unknown): u is C.Reference<any, any> => hasProperty(u, ReferenceTypeId)

const _empty = makeContext(new Map())

/** @internal */
Expand Down Expand Up @@ -192,30 +225,47 @@ export const add = dual<
return makeContext(map)
})

const defaultValueCache = globalValue("effect/Context/defaultValueCache", () => new Map<string, any>())
const getDefaultValue = (tag: C.Reference<any, any>) => {
if (defaultValueCache.has(tag.key)) {
return defaultValueCache.get(tag.key)
}
const value = tag.defaultValue()
defaultValueCache.set(tag.key, value)
return value
}

/** @internal */
export const unsafeGetReference = <Services, I, S>(self: C.Context<Services>, tag: C.Reference<I, S>): S => {
return self.unsafeMap.has(tag.key) ? self.unsafeMap.get(tag.key) : getDefaultValue(tag)
}

/** @internal */
export const unsafeGet = dual<
<S, I>(tag: C.Tag<I, S>) => <Services>(self: C.Context<Services>) => S,
<Services, S, I>(self: C.Context<Services>, tag: C.Tag<I, S>) => S
>(2, (self, tag) => {
if (!self.unsafeMap.has(tag.key)) {
throw serviceNotFoundError(tag as any)
return ReferenceTypeId in tag ? getDefaultValue(tag as any) : serviceNotFoundError(tag)
}
return self.unsafeMap.get(tag.key)! as any
})

/** @internal */
export const get: {
<I, S>(tag: C.Reference<I, S>): <Services>(self: C.Context<Services>) => S
<Services, T extends C.ValidTagsById<Services>>(tag: T): (self: C.Context<Services>) => C.Tag.Service<T>
<Services, I, S>(self: C.Context<Services>, tag: C.Reference<I, S>): S
<Services, T extends C.ValidTagsById<Services>>(self: C.Context<Services>, tag: T): C.Tag.Service<T>
} = unsafeGet
} = unsafeGet as any

/** @internal */
export const getOrElse = dual<
<S, I, B>(tag: C.Tag<I, S>, orElse: LazyArg<B>) => <Services>(self: C.Context<Services>) => S | B,
<Services, S, I, B>(self: C.Context<Services>, tag: C.Tag<I, S>, orElse: LazyArg<B>) => S | B
>(3, (self, tag, orElse) => {
if (!self.unsafeMap.has(tag.key)) {
return orElse()
return isReference(tag) ? getDefaultValue(tag) : orElse()
}
return self.unsafeMap.get(tag.key)! as any
})
Expand All @@ -226,7 +276,7 @@ export const getOption = dual<
<Services, S, I>(self: C.Context<Services>, tag: C.Tag<I, S>) => O.Option<S>
>(2, (self, tag) => {
if (!self.unsafeMap.has(tag.key)) {
return option.none
return isReference(tag) ? option.some(getDefaultValue(tag)) : option.none
}
return option.some(self.unsafeMap.get(tag.key)! as any)
})
Expand Down

0 comments on commit 82e2ac0

Please sign in to comment.