@radheim/util 0.0.0-stage → 2.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/abort.d.ts +1 -0
- package/dist/abort.js +8 -0
- package/dist/activity-calendar.d.ts +21 -0
- package/dist/activity-calendar.js +42 -0
- package/dist/artifact.d.ts +4 -0
- package/dist/artifact.js +85 -0
- package/dist/base64.d.ts +4 -0
- package/dist/base64.js +24 -0
- package/dist/binary.d.ts +7 -0
- package/dist/binary.js +34 -0
- package/dist/bom.d.ts +22 -0
- package/dist/bom.js +36 -0
- package/dist/cross-spawn-spawner.d.ts +9 -0
- package/dist/cross-spawn-spawner.js +548 -0
- package/dist/duration.d.ts +2 -0
- package/dist/duration.js +22 -0
- package/dist/effect/app-node-platform.d.ts +13 -0
- package/dist/effect/app-node-platform.js +29 -0
- package/dist/effect/app-node.d.ts +16 -0
- package/dist/effect/app-node.js +8 -0
- package/dist/effect/layer-node.d.ts +178 -0
- package/dist/effect/layer-node.js +248 -0
- package/dist/effect-flock.d.ts +31 -0
- package/dist/effect-flock.js +186 -0
- package/dist/encode.d.ts +4 -0
- package/dist/encode.js +38 -0
- package/dist/execute-output.d.ts +10 -0
- package/dist/execute-output.js +22 -0
- package/dist/flock.d.ts +28 -0
- package/dist/flock.js +267 -0
- package/dist/fs-util.d.ts +54 -0
- package/dist/fs-util.js +200 -0
- package/dist/glob.d.ts +18 -0
- package/dist/glob.js +29 -0
- package/dist/global-roots.d.ts +8 -0
- package/dist/global-roots.js +17 -0
- package/dist/global-roots.workerd.d.ts +7 -0
- package/dist/global-roots.workerd.js +15 -0
- package/dist/global.d.ts +30 -0
- package/dist/global.js +54 -0
- package/dist/hash.d.ts +4 -0
- package/dist/hash.js +12 -0
- package/dist/heap-snapshot.d.ts +19 -0
- package/dist/heap-snapshot.js +38 -0
- package/dist/no-timeout-fetch.d.ts +1 -0
- package/dist/no-timeout-fetch.js +4 -0
- package/dist/npm-config.d.ts +4 -0
- package/dist/npm-config.js +34 -0
- package/dist/npm.d.ts +45 -0
- package/dist/npm.js +441 -0
- package/dist/observability/logging.d.ts +14 -0
- package/dist/observability/logging.js +151 -0
- package/dist/observability/otlp.d.ts +19 -0
- package/dist/observability/otlp.js +63 -0
- package/dist/observability/shared.d.ts +1 -0
- package/dist/observability/shared.js +7 -0
- package/dist/observability/tracing.d.ts +2 -0
- package/dist/observability/tracing.js +3 -0
- package/dist/observability.d.ts +13 -0
- package/dist/observability.js +37 -0
- package/dist/open.d.ts +2 -0
- package/dist/open.js +10 -0
- package/dist/patch.d.ts +43 -0
- package/dist/patch.js +332 -0
- package/dist/path.d.ts +20 -0
- package/dist/path.js +134 -0
- package/dist/process-signal.d.ts +5 -0
- package/dist/process-signal.js +22 -0
- package/dist/process.d.ts +54 -0
- package/dist/process.js +167 -0
- package/dist/qr.d.ts +15 -0
- package/dist/qr.js +295 -0
- package/dist/record.d.ts +2 -0
- package/dist/record.js +2 -0
- package/dist/retry.d.ts +8 -0
- package/dist/retry.js +45 -0
- package/dist/runtime/import.bun.d.ts +2 -0
- package/dist/runtime/import.bun.js +8 -0
- package/dist/runtime/import.node.d.ts +2 -0
- package/dist/runtime/import.node.js +62 -0
- package/dist/runtime/import.workerd.d.ts +2 -0
- package/dist/runtime/import.workerd.js +7 -0
- package/dist/runtime-import.d.ts +1 -0
- package/dist/runtime-import.js +1 -0
- package/dist/session-mention.d.ts +11 -0
- package/dist/session-mention.js +18 -0
- package/dist/session-title-fallback.d.ts +16 -0
- package/dist/session-title-fallback.js +23 -0
- package/dist/session-turn.d.ts +37 -0
- package/dist/session-turn.js +56 -0
- package/dist/teardown.d.ts +8 -0
- package/dist/teardown.js +16 -0
- package/dist/text-boundary.d.ts +11 -0
- package/dist/text-boundary.js +22 -0
- package/dist/uuid.d.ts +1 -0
- package/dist/uuid.js +14 -0
- package/package.json +71 -4
- package/README.md +0 -3
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { Brand, Context, Layer } from "effect";
|
|
2
|
+
export * as LayerNode from "./layer-node.js";
|
|
3
|
+
declare const GraphTypeId: unique symbol;
|
|
4
|
+
declare const VarianceTypeId: unique symbol;
|
|
5
|
+
declare const NodeTypeId: unique symbol;
|
|
6
|
+
declare const ReplacementTypeId: unique symbol;
|
|
7
|
+
export type Tag<Name extends string = string> = Name & Brand.Brand<"LayerNode.Tag">;
|
|
8
|
+
export type Graph<A, E = never, T extends Tag | undefined = Tag | undefined> = GraphValue<A, E, T>;
|
|
9
|
+
export type Node<A, E = never, T extends Tag | undefined = undefined, HasService extends boolean = true> = NodeValue<A, E, T, HasService>;
|
|
10
|
+
export type Provider<A, E = never, T extends Tag | undefined = undefined, HasService extends boolean = true> = ProviderNode<A, E, T, HasService>;
|
|
11
|
+
export type Replacement = ReplacementValue;
|
|
12
|
+
export type Replacements = readonly Replacement[];
|
|
13
|
+
type AnyGraph = Graph<never, unknown>;
|
|
14
|
+
type AnyNode = AnyGraph & {
|
|
15
|
+
readonly [NodeTypeId]: unknown;
|
|
16
|
+
readonly tag: Tag | undefined;
|
|
17
|
+
};
|
|
18
|
+
type RuntimeLayer = Layer.Layer<never, unknown, unknown>;
|
|
19
|
+
type GraphList = readonly [] | readonly [AnyGraph, ...AnyGraph[]];
|
|
20
|
+
export type Output<Item> = CommonOutput<Item, Item extends Graph<infer A, unknown> ? A : never>;
|
|
21
|
+
type GraphError<Item> = Item extends Graph<never, infer E> ? E : never;
|
|
22
|
+
type GraphTag<Item> = Item extends Graph<never, unknown, infer T> ? T : never;
|
|
23
|
+
type CommonOutput<Item, A> = A extends unknown ? ([Item] extends [Graph<A, unknown>] ? A : never) : never;
|
|
24
|
+
type LayerOutput<Item extends Layer.Any, A = Layer.Success<Item>> = A extends unknown ? [Item] extends [Layer.Layer<A, unknown, unknown>] ? A : never : never;
|
|
25
|
+
type ListOutput<Items extends readonly AnyGraph[], A = never> = [Items] extends [
|
|
26
|
+
readonly [infer Head extends AnyGraph, ...infer Tail extends readonly AnyGraph[]]
|
|
27
|
+
] ? ListOutput<Tail, A | Output<Head>> : A;
|
|
28
|
+
type IsSingle<T, All = T> = 0 extends 1 & T ? false : [T] extends [never] ? false : T extends unknown ? [All] extends [T] ? true : false : false;
|
|
29
|
+
type MockShape<A> = [IsSingle<A>] extends [true] ? [A] extends [Context.ServiceClass.Shape<string, infer S>] ? [S] extends [object] ? S : never : [A] extends [object] ? A : never : never;
|
|
30
|
+
type HasServiceKey<Service> = [Service] extends [never] ? false : true;
|
|
31
|
+
type Definition = {
|
|
32
|
+
readonly kind: "group";
|
|
33
|
+
readonly name: string;
|
|
34
|
+
readonly dependencies: readonly AnyGraph[];
|
|
35
|
+
readonly service?: undefined;
|
|
36
|
+
} | {
|
|
37
|
+
readonly kind: "unbound";
|
|
38
|
+
readonly name: string;
|
|
39
|
+
readonly service: Context.Service.Any;
|
|
40
|
+
} | {
|
|
41
|
+
readonly kind: "layer";
|
|
42
|
+
readonly name: string;
|
|
43
|
+
readonly implementation: RuntimeLayer;
|
|
44
|
+
readonly dependencies: readonly AnyGraph[];
|
|
45
|
+
readonly service?: Context.Service.Any;
|
|
46
|
+
};
|
|
47
|
+
declare class GraphValue<in A, out E, out T extends Tag | undefined> {
|
|
48
|
+
private readonly graph;
|
|
49
|
+
readonly [VarianceTypeId]: {
|
|
50
|
+
readonly output: (_: A) => void;
|
|
51
|
+
readonly error: () => E;
|
|
52
|
+
readonly tags: () => T;
|
|
53
|
+
};
|
|
54
|
+
readonly [GraphTypeId]: Definition;
|
|
55
|
+
constructor(definition: Definition);
|
|
56
|
+
get name(): string;
|
|
57
|
+
}
|
|
58
|
+
declare class NodeValue<in out A, in out E, in out T extends Tag | undefined, HasService extends boolean = true> extends GraphValue<A, E, T> {
|
|
59
|
+
readonly tag: T;
|
|
60
|
+
readonly [NodeTypeId]: (_: [A, E, T]) => [A, E, T];
|
|
61
|
+
private readonly hasService;
|
|
62
|
+
constructor(definition: Exclude<Definition, {
|
|
63
|
+
kind: "group";
|
|
64
|
+
}>, tag: T);
|
|
65
|
+
/** The service this node was declared for. Only nodes declared with a `service` have one. */
|
|
66
|
+
get service(): HasService extends true ? Context.Key<A, unknown> : undefined;
|
|
67
|
+
/** Replace this declaration, including every dependency on it, without acquiring its old wiring. */
|
|
68
|
+
replace<const Target extends AnyNode | Layer.Any>(this: Node<A, E, T, boolean>, replacement: Target & CheckReplacement<A, E, T, Target>): Replacement;
|
|
69
|
+
/** Replace this single-service declaration with a partial mock backed by `Layer.mock`. */
|
|
70
|
+
mock(this: [HasService] extends [true] ? ([MockShape<A>] extends [never] ? never : Node<A, E, T, true>) : never, implementation: Layer.PartialEffectful<MockShape<A>>): Replacement;
|
|
71
|
+
}
|
|
72
|
+
declare class ProviderNode<in out A, in out E, in out T extends Tag | undefined, HasService extends boolean = true> extends NodeValue<A, E, T, HasService> {
|
|
73
|
+
/** Decorate the implementation while preserving its dependency wiring and service contract. */
|
|
74
|
+
mapLayer(this: Provider<A, E, T, HasService>, f: <R>(layer: Layer.Layer<A, E, R>) => Layer.Layer<A, E, R>): Provider<A, E, T, HasService>;
|
|
75
|
+
}
|
|
76
|
+
declare class ReplacementValue {
|
|
77
|
+
private readonly checked;
|
|
78
|
+
readonly [ReplacementTypeId]: {
|
|
79
|
+
readonly source: AnyNode;
|
|
80
|
+
readonly target: AnyNode;
|
|
81
|
+
};
|
|
82
|
+
constructor(source: AnyNode, target: AnyNode);
|
|
83
|
+
}
|
|
84
|
+
type CheckErrors<Expected, Actual> = [Exclude<Actual, Expected>] extends [never] ? never : {
|
|
85
|
+
readonly "New replacement errors": Exclude<Actual, Expected>;
|
|
86
|
+
};
|
|
87
|
+
type CheckReplacement<A, E, T, Target> = [ReplacementErrors<A, E, T, Target>] extends [never] ? unknown : ReplacementErrors<A, E, T, Target>;
|
|
88
|
+
type ReplacementErrors<A, E, T, Target> = Target extends AnyNode ? [Exclude<A, Output<Target>>] extends [never] ? [GraphTag<Target>] extends [T] ? CheckErrors<E, GraphError<Target>> : {
|
|
89
|
+
readonly "Invalid replacement tag": GraphTag<Target>;
|
|
90
|
+
} : {
|
|
91
|
+
readonly "Missing replacement outputs": Exclude<A, Output<Target>>;
|
|
92
|
+
} : Target extends Layer.Layer<A, infer E2, never> ? CheckErrors<E, E2> : {
|
|
93
|
+
readonly "Replacement must be a closed layer": Target;
|
|
94
|
+
};
|
|
95
|
+
type CheckDependencies<Implementation extends Layer.Any, Items extends GraphList> = [
|
|
96
|
+
Exclude<Layer.Services<Implementation>, ListOutput<Items>>
|
|
97
|
+
] extends [never] ? unknown : {
|
|
98
|
+
readonly "Missing dependencies": Exclude<Layer.Services<Implementation>, ListOutput<Items>>;
|
|
99
|
+
};
|
|
100
|
+
type CheckService<Implementation extends Layer.Any, Service, Id = Context.Service.Identifier<Service>> = [
|
|
101
|
+
Service
|
|
102
|
+
] extends [never] ? unknown : [Id] extends [never] ? [LayerOutput<Implementation>] extends [never] ? unknown : {
|
|
103
|
+
readonly "Extra layer outputs require a named node": LayerOutput<Implementation>;
|
|
104
|
+
} : [IsSingle<Id>] extends [true] ? [Exclude<Id, LayerOutput<Implementation>>] extends [never] ? [Exclude<LayerOutput<Implementation>, Id>] extends [never] ? unknown : {
|
|
105
|
+
readonly "Extra layer outputs require a named node": Exclude<LayerOutput<Implementation>, Id>;
|
|
106
|
+
} : {
|
|
107
|
+
readonly "Service must be provided by layer": Id;
|
|
108
|
+
} : {
|
|
109
|
+
readonly "Service must be a single service key": Service;
|
|
110
|
+
};
|
|
111
|
+
type Identity<Service extends Context.Service.Any> = {
|
|
112
|
+
readonly service: Service;
|
|
113
|
+
readonly name?: never;
|
|
114
|
+
} | {
|
|
115
|
+
readonly name: string;
|
|
116
|
+
readonly service?: never;
|
|
117
|
+
};
|
|
118
|
+
type CheckLayer<Implementation> = [Implementation] extends [RuntimeLayer] ? unknown : {
|
|
119
|
+
readonly "Layer contract must be preserved": Implementation;
|
|
120
|
+
};
|
|
121
|
+
type TagInput<T> = {
|
|
122
|
+
readonly tag: T;
|
|
123
|
+
} | ([T] extends [undefined] ? {
|
|
124
|
+
readonly tag?: undefined;
|
|
125
|
+
} : never);
|
|
126
|
+
type BaseInput<Implementation extends Layer.Any, Items extends GraphList, Service extends Context.Service.Any> = Identity<Service> & {
|
|
127
|
+
readonly layer: Implementation & CheckLayer<NoInfer<Implementation>> & CheckService<NoInfer<Implementation>, NoInfer<Service>>;
|
|
128
|
+
readonly deps: Items & CheckDependencies<Implementation, NoInfer<Items>>;
|
|
129
|
+
};
|
|
130
|
+
export type TagConfig = Readonly<Record<string, readonly string[]>>;
|
|
131
|
+
type TagNames<Config extends TagConfig> = keyof Config & string;
|
|
132
|
+
type CheckTags<Items extends GraphList, Names extends string> = [
|
|
133
|
+
Exclude<GraphTag<Items[number]>, Tag<Names> | undefined>
|
|
134
|
+
] extends [never] ? unknown : {
|
|
135
|
+
readonly "Invalid tag dependencies": Exclude<GraphTag<Items[number]>, Tag<Names> | undefined>;
|
|
136
|
+
};
|
|
137
|
+
export interface Tags<Config extends TagConfig> {
|
|
138
|
+
readonly values: {
|
|
139
|
+
readonly [Name in TagNames<Config>]: Tag<Name>;
|
|
140
|
+
};
|
|
141
|
+
readonly make: <Name extends TagNames<Config>>(name: Name) => TagMaker<Config, Name>;
|
|
142
|
+
}
|
|
143
|
+
export type TagMaker<Config extends TagConfig, Name extends TagNames<Config>> = <const Implementation extends Layer.Any, const Items extends GraphList, const Service extends Context.Service.Any = never>(input: BaseInput<Implementation, Items, Service> & CheckTags<Items, Name | Config[Name][number]>) => Provider<LayerOutput<Implementation>, Layer.Error<Implementation> | GraphError<Items[number]>, Tag<Name>, HasServiceKey<Service>>;
|
|
144
|
+
export declare function tags<const Config extends {
|
|
145
|
+
readonly [Name in keyof Config]: readonly (keyof Config & string)[];
|
|
146
|
+
}>(config: Config): Tags<Config>;
|
|
147
|
+
export declare function make<const Implementation extends Layer.Any, const Items extends GraphList, const T extends Tag | undefined = undefined, const Service extends Context.Service.Any = never>(input: BaseInput<Implementation, Items, Service> & TagInput<T>): Provider<LayerOutput<Implementation>, Layer.Error<Implementation> | GraphError<Items[number]>, T, HasServiceKey<Service>>;
|
|
148
|
+
export declare function unbound<R, Shape, const T extends Tag>(service: Context.Key<R, Shape> & ([IsSingle<NoInfer<R>>] extends [true] ? unknown : {
|
|
149
|
+
readonly "Service must be a single service key": NoInfer<R>;
|
|
150
|
+
}), tag: T): Node<R, never, T>;
|
|
151
|
+
/** Ordered, associative composition. Only these roots' outputs are exposed; their dependencies remain private. */
|
|
152
|
+
export declare function group<const Items extends readonly AnyGraph[]>(dependencies: Items): Graph<ListOutput<Items>, GraphError<Items[number]>, GraphTag<Items[number]>>;
|
|
153
|
+
export interface CompileOptions {
|
|
154
|
+
readonly replacements?: Replacements;
|
|
155
|
+
/** Share subgraphs rooted at this tag; give the remaining wiring a fresh map for each build. */
|
|
156
|
+
readonly shared?: Tag;
|
|
157
|
+
}
|
|
158
|
+
export interface Host<T extends Tag = Tag> {
|
|
159
|
+
readonly tag: T;
|
|
160
|
+
/** What the host built for the `tag` nodes its children reach (see `tagged`). */
|
|
161
|
+
readonly context: Context.Context<never>;
|
|
162
|
+
/** The host's replacements: its `tag` ones are already built into `context`, the rest apply to children too. */
|
|
163
|
+
readonly replacements?: Replacements;
|
|
164
|
+
}
|
|
165
|
+
export interface ChildOptions {
|
|
166
|
+
readonly host: Host;
|
|
167
|
+
/** This child's own replacements, applied after `host.replacements`. They cannot target `host.tag` nodes. */
|
|
168
|
+
readonly replacements?: Replacements;
|
|
169
|
+
}
|
|
170
|
+
/** Every `tag` node `root` reaches, after `replacements`, including transitive `tag` dependencies. */
|
|
171
|
+
export declare function tagged(root: Graph<never, unknown>, tag: Tag, replacements?: Replacements): Graph<never, unknown, Tag<string> | undefined>[];
|
|
172
|
+
/** Resolve the final overrides before validating or acquiring anything. Effect owns acquisition and finalization. */
|
|
173
|
+
export declare function compile<A, E>(root: Graph<A, E>, options?: CompileOptions): Layer.Layer<A, E>;
|
|
174
|
+
/**
|
|
175
|
+
* Compile a graph that stands on a host: every `host.tag` node reads its service from `host.context` instead of
|
|
176
|
+
* being built, so children never acquire, retain, or release the host's services. The rest is fresh for each build.
|
|
177
|
+
*/
|
|
178
|
+
export declare function compileChild<A, E>(root: Graph<A, E>, options: ChildOptions): Layer.Layer<A, E>;
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { Brand, Context, Effect, Layer, Scope } from "effect";
|
|
2
|
+
import { Teardown } from "../teardown.js";
|
|
3
|
+
export * as LayerNode from "./layer-node.js";
|
|
4
|
+
const GraphTypeId = Symbol("LayerNode.Graph");
|
|
5
|
+
const VarianceTypeId = Symbol("LayerNode.Variance");
|
|
6
|
+
const NodeTypeId = Symbol("LayerNode.Node");
|
|
7
|
+
const ReplacementTypeId = Symbol("LayerNode.Replacement");
|
|
8
|
+
const makeTag = Brand.nominal();
|
|
9
|
+
class GraphValue {
|
|
10
|
+
[GraphTypeId];
|
|
11
|
+
constructor(definition) {
|
|
12
|
+
this[GraphTypeId] = definition;
|
|
13
|
+
}
|
|
14
|
+
get name() {
|
|
15
|
+
return this[GraphTypeId].name;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
class NodeValue extends GraphValue {
|
|
19
|
+
tag;
|
|
20
|
+
constructor(definition, tag) {
|
|
21
|
+
super(definition);
|
|
22
|
+
this.tag = tag;
|
|
23
|
+
}
|
|
24
|
+
/** The service this node was declared for. Only nodes declared with a `service` have one. */
|
|
25
|
+
get service() {
|
|
26
|
+
return this[GraphTypeId].service;
|
|
27
|
+
}
|
|
28
|
+
/** Replace this declaration, including every dependency on it, without acquiring its old wiring. */
|
|
29
|
+
replace(replacement) {
|
|
30
|
+
if (replacement instanceof NodeValue) {
|
|
31
|
+
if (replacement.tag !== this.tag)
|
|
32
|
+
throw new Error(`Cannot replace ${this.name} across tags`);
|
|
33
|
+
return new ReplacementValue(this, replacement);
|
|
34
|
+
}
|
|
35
|
+
if (!Layer.isLayer(replacement))
|
|
36
|
+
throw new Error("A replacement must be a node or an Effect Layer");
|
|
37
|
+
return new ReplacementValue(this, makeProvider({ name: this.name, layer: replacement, deps: [] }, this.tag));
|
|
38
|
+
}
|
|
39
|
+
/** Replace this single-service declaration with a partial mock backed by `Layer.mock`. */
|
|
40
|
+
mock(implementation) {
|
|
41
|
+
const service = this.service;
|
|
42
|
+
if (!service)
|
|
43
|
+
throw new Error(`Cannot mock layer node without a service: ${this.name}`);
|
|
44
|
+
return new ReplacementValue(this, makeProvider({
|
|
45
|
+
service,
|
|
46
|
+
layer: Layer.mock(service, implementation),
|
|
47
|
+
deps: [],
|
|
48
|
+
}, this.tag));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
class ProviderNode extends NodeValue {
|
|
52
|
+
/** Decorate the implementation while preserving its dependency wiring and service contract. */
|
|
53
|
+
mapLayer(f) {
|
|
54
|
+
const definition = this[GraphTypeId];
|
|
55
|
+
if (definition.kind !== "layer")
|
|
56
|
+
throw new Error(`Cannot map unbound layer node: ${this.name}`);
|
|
57
|
+
return new ProviderNode({ ...definition, implementation: f(definition.implementation) }, this.tag);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
class ReplacementValue {
|
|
61
|
+
[ReplacementTypeId];
|
|
62
|
+
constructor(source, target) {
|
|
63
|
+
this[ReplacementTypeId] = { source, target };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
export function tags(config) {
|
|
67
|
+
const values = Object.fromEntries(Object.keys(config).map((name) => [name, makeTag(name)]));
|
|
68
|
+
return {
|
|
69
|
+
values,
|
|
70
|
+
make: (name) => ((input) => makeProvider(input, values[name])),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
export function make(input) {
|
|
74
|
+
return makeProvider(input, input.tag);
|
|
75
|
+
}
|
|
76
|
+
function makeProvider(input, tag) {
|
|
77
|
+
if (!Layer.isLayer(input.layer))
|
|
78
|
+
throw new Error("A layer node requires an Effect Layer");
|
|
79
|
+
return new ProviderNode({
|
|
80
|
+
kind: "layer",
|
|
81
|
+
name: input.service !== undefined ? input.service.key : input.name,
|
|
82
|
+
implementation: input.layer,
|
|
83
|
+
dependencies: [...input.deps],
|
|
84
|
+
service: input.service,
|
|
85
|
+
}, tag);
|
|
86
|
+
}
|
|
87
|
+
export function unbound(service, tag) {
|
|
88
|
+
return new NodeValue({ kind: "unbound", name: service.key, service }, tag);
|
|
89
|
+
}
|
|
90
|
+
/** Ordered, associative composition. Only these roots' outputs are exposed; their dependencies remain private. */
|
|
91
|
+
export function group(dependencies) {
|
|
92
|
+
return new GraphValue({ kind: "group", name: "group", dependencies: [...dependencies] });
|
|
93
|
+
}
|
|
94
|
+
/** Every `tag` node `root` reaches, after `replacements`, including transitive `tag` dependencies. */
|
|
95
|
+
export function tagged(root, tag, replacements = []) {
|
|
96
|
+
const targets = replacementTargets(replacements);
|
|
97
|
+
const seen = new Set();
|
|
98
|
+
const found = [];
|
|
99
|
+
const visit = (graph) => {
|
|
100
|
+
if (seen.has(graph))
|
|
101
|
+
return;
|
|
102
|
+
seen.add(graph);
|
|
103
|
+
const replacement = targets.get(graph);
|
|
104
|
+
if (replacement && replacement !== graph)
|
|
105
|
+
return visit(replacement);
|
|
106
|
+
if (graph instanceof NodeValue && graph.tag === tag)
|
|
107
|
+
found.push(graph);
|
|
108
|
+
const definition = graph[GraphTypeId];
|
|
109
|
+
if (definition.kind !== "unbound")
|
|
110
|
+
definition.dependencies.forEach(visit);
|
|
111
|
+
};
|
|
112
|
+
visit(root);
|
|
113
|
+
return found;
|
|
114
|
+
}
|
|
115
|
+
/** Resolve the final overrides before validating or acquiring anything. Effect owns acquisition and finalization. */
|
|
116
|
+
export function compile(root, options = {}) {
|
|
117
|
+
return compileGraph(root, options.replacements ?? [], options.shared);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Compile a graph that stands on a host: every `host.tag` node reads its service from `host.context` instead of
|
|
121
|
+
* being built, so children never acquire, retain, or release the host's services. The rest is fresh for each build.
|
|
122
|
+
*/
|
|
123
|
+
export function compileChild(root, options) {
|
|
124
|
+
const own = options.replacements ?? [];
|
|
125
|
+
const rejected = own.find((item) => item[ReplacementTypeId].source.tag === options.host.tag);
|
|
126
|
+
if (rejected) {
|
|
127
|
+
throw new Error(`Cannot replace ${rejected[ReplacementTypeId].source.name} in a child graph: its host builds ${options.host.tag} nodes`);
|
|
128
|
+
}
|
|
129
|
+
return compileGraph(root, [...(options.host.replacements ?? []), ...own], undefined, options.host);
|
|
130
|
+
}
|
|
131
|
+
function replacementTargets(replacements) {
|
|
132
|
+
return new Map(replacements.map((item) => {
|
|
133
|
+
const replacement = item[ReplacementTypeId];
|
|
134
|
+
return [replacement.source, replacement.target];
|
|
135
|
+
}));
|
|
136
|
+
}
|
|
137
|
+
function compileGraph(root, list, shared, host) {
|
|
138
|
+
const replacements = replacementTargets(list);
|
|
139
|
+
const makeDomain = (isShared) => ({
|
|
140
|
+
shared: isShared,
|
|
141
|
+
cache: new Map(),
|
|
142
|
+
definitions: new Map(),
|
|
143
|
+
});
|
|
144
|
+
const domains = { shared: makeDomain(true), local: makeDomain(false) };
|
|
145
|
+
const stack = [];
|
|
146
|
+
const resolveDefinition = (graph, domain) => {
|
|
147
|
+
// Host nodes keep their tag through any replacement, so the host's choice is already in its context.
|
|
148
|
+
if (host && graph instanceof NodeValue && graph.tag === host.tag)
|
|
149
|
+
return [borrow(graph, host.context)];
|
|
150
|
+
const replacement = replacements.get(graph);
|
|
151
|
+
if (replacement && replacement !== graph)
|
|
152
|
+
return resolve(replacement, domain);
|
|
153
|
+
const definition = graph[GraphTypeId];
|
|
154
|
+
if (definition.kind === "group")
|
|
155
|
+
return definition.dependencies.flatMap((dependency) => resolve(dependency, domain));
|
|
156
|
+
if (definition.kind === "unbound")
|
|
157
|
+
throw new Error(`Unbound layer node: ${definition.name}`);
|
|
158
|
+
const dependencies = definition.dependencies.flatMap((dependency) => resolve(dependency, domain));
|
|
159
|
+
const existing = domain.definitions.get(definition.implementation);
|
|
160
|
+
if (!existing) {
|
|
161
|
+
const node = {
|
|
162
|
+
name: definition.name,
|
|
163
|
+
implementation: definition.implementation,
|
|
164
|
+
dependencies,
|
|
165
|
+
shared: domain.shared,
|
|
166
|
+
};
|
|
167
|
+
domain.definitions.set(definition.implementation, node);
|
|
168
|
+
return [node];
|
|
169
|
+
}
|
|
170
|
+
if (existing.dependencies.length !== dependencies.length ||
|
|
171
|
+
existing.dependencies.some((dependency, index) => dependency !== dependencies[index])) {
|
|
172
|
+
throw new Error(`Layer ${definition.name} is wired to different dependencies; use a distinct implementation Layer`);
|
|
173
|
+
}
|
|
174
|
+
return [existing];
|
|
175
|
+
};
|
|
176
|
+
const resolve = (graph, domain = domains.local) => {
|
|
177
|
+
const current = domain.shared || (shared !== undefined && graph instanceof NodeValue && graph.tag === shared)
|
|
178
|
+
? domains.shared
|
|
179
|
+
: domains.local;
|
|
180
|
+
const cached = current.cache.get(graph);
|
|
181
|
+
if (cached)
|
|
182
|
+
return cached;
|
|
183
|
+
const cycle = stack.indexOf(graph);
|
|
184
|
+
if (cycle !== -1) {
|
|
185
|
+
throw new Error(`Cycle detected in layer graph: ${[...stack.slice(cycle), graph].map((item) => item.name).join(" -> ")}`);
|
|
186
|
+
}
|
|
187
|
+
stack.push(graph);
|
|
188
|
+
const result = resolveDefinition(graph, current);
|
|
189
|
+
stack.pop();
|
|
190
|
+
current.cache.set(graph, result);
|
|
191
|
+
return result;
|
|
192
|
+
};
|
|
193
|
+
const roots = resolve(root);
|
|
194
|
+
return Layer.fromBuild((memoMap, scope) => {
|
|
195
|
+
const local = shared === undefined && host === undefined ? memoMap : Layer.makeMemoMapUnsafe();
|
|
196
|
+
const ambient = Layer.succeed(Layer.CurrentMemoMap, memoMap);
|
|
197
|
+
const layers = new Map();
|
|
198
|
+
const build = (node) => {
|
|
199
|
+
if (node.borrowed)
|
|
200
|
+
return node.implementation;
|
|
201
|
+
const cached = layers.get(node);
|
|
202
|
+
if (cached)
|
|
203
|
+
return cached;
|
|
204
|
+
const dependencies = node.dependencies.map(build);
|
|
205
|
+
// Acquisition uses the selected cache, while lazy LayerMaps inherit the enclosing shared cache.
|
|
206
|
+
const implementation = Layer.suspend(() => node.implementation.pipe(Layer.provide([ambient, ...dependencies])));
|
|
207
|
+
const layer = Layer.fromBuild((_, scope) => trackRelease(node.name, scope, () => buildContext(implementation, node.shared ? memoMap : local, scope)));
|
|
208
|
+
layers.set(node, layer);
|
|
209
|
+
return layer;
|
|
210
|
+
};
|
|
211
|
+
return buildContext(roots.map(build).reduce((result, layer) => layer.pipe(Layer.provideMerge(result)), Layer.empty), memoMap, scope);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
function borrow(node, context) {
|
|
215
|
+
const service = node[GraphTypeId].service;
|
|
216
|
+
const value = service && Context.getOrUndefined(context, service);
|
|
217
|
+
if (service && value === undefined) {
|
|
218
|
+
throw new Error(`Host context is missing ${node.name}; build it on the host before its children`);
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
name: node.name,
|
|
222
|
+
// Side-effect-only host nodes (`service === undefined`) already ran on the host and expose no service output.
|
|
223
|
+
implementation: service ? Layer.succeedContext(Context.make(service, value)) : Layer.empty,
|
|
224
|
+
dependencies: [],
|
|
225
|
+
shared: false,
|
|
226
|
+
borrowed: true,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
// The node's scope releases sequentially in reverse order, so a finalizer added before the build runs last and one
|
|
230
|
+
// added after it runs first: together they bracket the release of everything this node acquired. The build must
|
|
231
|
+
// not start before the first finalizer is added; Layer builds fork their scopes as soon as they are called.
|
|
232
|
+
function trackRelease(name, scope, build) {
|
|
233
|
+
return Effect.gen(function* () {
|
|
234
|
+
let settle = () => { };
|
|
235
|
+
yield* Scope.addFinalizer(scope, Effect.sync(() => settle()));
|
|
236
|
+
const result = yield* build();
|
|
237
|
+
yield* Scope.addFinalizer(scope, Effect.sync(() => {
|
|
238
|
+
settle = Teardown.track(`layer ${name} releasing`);
|
|
239
|
+
}));
|
|
240
|
+
return result;
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
class BuildResult extends Context.Service()("@radheim/LayerNode/BuildResult") {
|
|
244
|
+
}
|
|
245
|
+
function buildContext(layer, memoMap, scope) {
|
|
246
|
+
// Preserve the exact output context before Effect appends its own memo-map metadata.
|
|
247
|
+
return Layer.buildWithMemoMap(layer.pipe(Layer.flatMap((context) => Layer.succeed(BuildResult, context))), memoMap, scope).pipe(Effect.map(Context.get(BuildResult)));
|
|
248
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Context, Effect, Schema } from "effect";
|
|
2
|
+
import type { Scope } from "effect";
|
|
3
|
+
export declare namespace EffectFlock {
|
|
4
|
+
const LockTimeoutError_base: Schema.Class<LockTimeoutError, Schema.TaggedStruct<"LockTimeoutError", {
|
|
5
|
+
readonly key: Schema.String;
|
|
6
|
+
}>, import("effect/Cause").YieldableError>;
|
|
7
|
+
export class LockTimeoutError extends LockTimeoutError_base {
|
|
8
|
+
}
|
|
9
|
+
const LockCompromisedError_base: Schema.Class<LockCompromisedError, Schema.TaggedStruct<"LockCompromisedError", {
|
|
10
|
+
readonly detail: Schema.String;
|
|
11
|
+
}>, import("effect/Cause").YieldableError>;
|
|
12
|
+
export class LockCompromisedError extends LockCompromisedError_base {
|
|
13
|
+
}
|
|
14
|
+
export type LockError = LockTimeoutError | LockCompromisedError;
|
|
15
|
+
export interface Options {
|
|
16
|
+
readonly staleMs?: number;
|
|
17
|
+
readonly timeoutMs?: number;
|
|
18
|
+
}
|
|
19
|
+
export interface Interface {
|
|
20
|
+
readonly acquire: (key: string, dir?: string, options?: Options) => Effect.Effect<void, LockError, Scope.Scope>;
|
|
21
|
+
readonly withLock: {
|
|
22
|
+
(key: string, dir?: string): <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E | LockError, R>;
|
|
23
|
+
<A, E, R>(body: Effect.Effect<A, E, R>, key: string, dir?: string): Effect.Effect<A, E | LockError, R>;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
const Service_base: Context.ServiceClass<Service, "EffectFlock", Interface>;
|
|
27
|
+
export class Service extends Service_base {
|
|
28
|
+
}
|
|
29
|
+
export const node: import("./effect/layer-node.js").Provider<Service, never, import("./effect/layer-node.js").Tag<"global">, true>;
|
|
30
|
+
export {};
|
|
31
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import path from "path";
|
|
2
|
+
import os from "os";
|
|
3
|
+
import { randomUUID } from "crypto";
|
|
4
|
+
import { Context, Effect, Function, Layer, Option, Schedule, Schema } from "effect";
|
|
5
|
+
import { FSUtil } from "./fs-util.js";
|
|
6
|
+
import { Global } from "./global.js";
|
|
7
|
+
import { makeGlobalNode } from "./effect/app-node.js";
|
|
8
|
+
import { Hash } from "./hash.js";
|
|
9
|
+
export var EffectFlock;
|
|
10
|
+
(function (EffectFlock) {
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
// Errors
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
class LockTimeoutError extends Schema.TaggedError()("LockTimeoutError", {
|
|
15
|
+
key: Schema.String,
|
|
16
|
+
}) {
|
|
17
|
+
}
|
|
18
|
+
EffectFlock.LockTimeoutError = LockTimeoutError;
|
|
19
|
+
class LockCompromisedError extends Schema.TaggedError()("LockCompromisedError", {
|
|
20
|
+
detail: Schema.String,
|
|
21
|
+
}) {
|
|
22
|
+
}
|
|
23
|
+
EffectFlock.LockCompromisedError = LockCompromisedError;
|
|
24
|
+
class ReleaseError extends Schema.TaggedError()("ReleaseError", {
|
|
25
|
+
detail: Schema.String,
|
|
26
|
+
cause: Schema.optional(Schema.Defect()),
|
|
27
|
+
}) {
|
|
28
|
+
get message() {
|
|
29
|
+
return this.detail;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Internal: signals "lock is held, retry later". Never leaks to callers. */
|
|
33
|
+
class NotAcquired extends Schema.TaggedError()("NotAcquired", {}) {
|
|
34
|
+
}
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
// Timing defaults
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
const DEFAULT_STALE_MS = 60_000;
|
|
39
|
+
const DEFAULT_TIMEOUT_MS = 5 * 60_000;
|
|
40
|
+
const BASE_DELAY_MS = 100;
|
|
41
|
+
const MAX_DELAY_MS = 2_000;
|
|
42
|
+
const retrySchedule = (timeoutMs) => Schedule.min([
|
|
43
|
+
Schedule.exponential(BASE_DELAY_MS, 1.7),
|
|
44
|
+
Schedule.spaced(Math.min(MAX_DELAY_MS, Math.max(BASE_DELAY_MS, Math.floor(timeoutMs / 10)))),
|
|
45
|
+
]).pipe(Schedule.jittered, Schedule.while((meta) => meta.elapsed < timeoutMs));
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
// Lock metadata schema
|
|
48
|
+
// ---------------------------------------------------------------------------
|
|
49
|
+
const LockMetaJson = Schema.fromJsonString(Schema.Struct({
|
|
50
|
+
token: Schema.String,
|
|
51
|
+
pid: Schema.Number,
|
|
52
|
+
hostname: Schema.String,
|
|
53
|
+
createdAt: Schema.String,
|
|
54
|
+
}));
|
|
55
|
+
const decodeMeta = Schema.decodeUnknownSync(LockMetaJson);
|
|
56
|
+
const encodeMeta = Schema.encodeSync(LockMetaJson);
|
|
57
|
+
class Service extends Context.Service()("EffectFlock") {
|
|
58
|
+
}
|
|
59
|
+
EffectFlock.Service = Service;
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
// Layer
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
function wall() {
|
|
64
|
+
return performance.timeOrigin + performance.now();
|
|
65
|
+
}
|
|
66
|
+
const mtimeMs = (info) => Option.getOrElse(info.mtime, () => new Date(0)).getTime();
|
|
67
|
+
const isPathGone = (e) => e.reason._tag === "NotFound" || e.reason._tag === "Unknown";
|
|
68
|
+
const layer = Layer.effect(Service, Effect.gen(function* () {
|
|
69
|
+
const global = yield* Global.Service;
|
|
70
|
+
const fs = yield* FSUtil.Service;
|
|
71
|
+
const lockRoot = path.join(global.state, "locks");
|
|
72
|
+
const hostname = os.hostname();
|
|
73
|
+
const ensuredDirs = new Set();
|
|
74
|
+
// -- helpers (close over fs) --
|
|
75
|
+
const safeStat = (file) => fs.stat(file).pipe(Effect.catchIf(isPathGone, () => Effect.void), Effect.orDie);
|
|
76
|
+
const forceRemove = (target) => fs.remove(target, { recursive: true }).pipe(Effect.ignore);
|
|
77
|
+
/** Atomic mkdir — returns true if created, false if already exists, dies on other errors. */
|
|
78
|
+
const atomicMkdir = (dir) => fs.makeDirectory(dir, { mode: 0o700 }).pipe(Effect.as(true), Effect.catchIf((e) => e.reason._tag === "AlreadyExists", () => Effect.succeed(false)), Effect.orDie);
|
|
79
|
+
/** Write with exclusive create — compromised error if file already exists. */
|
|
80
|
+
const exclusiveWrite = (filePath, content, lockDir, detail) => fs.writeFileString(filePath, content, { flag: "wx" }).pipe(Effect.catch(() => Effect.gen(function* () {
|
|
81
|
+
yield* forceRemove(lockDir);
|
|
82
|
+
return yield* new LockCompromisedError({ detail });
|
|
83
|
+
})));
|
|
84
|
+
const cleanStaleBreaker = Effect.fnUntraced(function* (breakerPath, staleMs) {
|
|
85
|
+
const bs = yield* safeStat(breakerPath);
|
|
86
|
+
if (bs && wall() - mtimeMs(bs) > staleMs)
|
|
87
|
+
yield* forceRemove(breakerPath);
|
|
88
|
+
return false;
|
|
89
|
+
});
|
|
90
|
+
const ensureDir = Effect.fnUntraced(function* (dir) {
|
|
91
|
+
if (ensuredDirs.has(dir))
|
|
92
|
+
return;
|
|
93
|
+
yield* fs.makeDirectory(dir, { recursive: true }).pipe(Effect.orDie);
|
|
94
|
+
ensuredDirs.add(dir);
|
|
95
|
+
});
|
|
96
|
+
const isStale = Effect.fnUntraced(function* (lockDir, heartbeatPath, metaPath, staleMs) {
|
|
97
|
+
const now = wall();
|
|
98
|
+
const hb = yield* safeStat(heartbeatPath);
|
|
99
|
+
if (hb)
|
|
100
|
+
return now - mtimeMs(hb) > staleMs;
|
|
101
|
+
const meta = yield* safeStat(metaPath);
|
|
102
|
+
if (meta)
|
|
103
|
+
return now - mtimeMs(meta) > staleMs;
|
|
104
|
+
const dir = yield* safeStat(lockDir);
|
|
105
|
+
if (!dir)
|
|
106
|
+
return false;
|
|
107
|
+
return now - mtimeMs(dir) > staleMs;
|
|
108
|
+
});
|
|
109
|
+
const tryAcquireLockDir = (lockDir, key, staleMs) => Effect.gen(function* () {
|
|
110
|
+
const token = randomUUID();
|
|
111
|
+
const metaPath = path.join(lockDir, "meta.json");
|
|
112
|
+
const heartbeatPath = path.join(lockDir, "heartbeat");
|
|
113
|
+
// Atomic mkdir — the POSIX lock primitive
|
|
114
|
+
const created = yield* atomicMkdir(lockDir);
|
|
115
|
+
if (!created) {
|
|
116
|
+
if (!(yield* isStale(lockDir, heartbeatPath, metaPath, staleMs)))
|
|
117
|
+
return yield* new NotAcquired();
|
|
118
|
+
// Stale — race for breaker ownership
|
|
119
|
+
const breakerPath = lockDir + ".breaker";
|
|
120
|
+
const claimed = yield* fs.makeDirectory(breakerPath, { mode: 0o700 }).pipe(Effect.as(true), Effect.catchIf((e) => e.reason._tag === "AlreadyExists", () => cleanStaleBreaker(breakerPath, staleMs)), Effect.catchIf(isPathGone, () => Effect.succeed(false)), Effect.orDie);
|
|
121
|
+
if (!claimed)
|
|
122
|
+
return yield* new NotAcquired();
|
|
123
|
+
// We own the breaker — double-check staleness, nuke, recreate
|
|
124
|
+
const recreated = yield* Effect.gen(function* () {
|
|
125
|
+
if (!(yield* isStale(lockDir, heartbeatPath, metaPath, staleMs)))
|
|
126
|
+
return false;
|
|
127
|
+
yield* forceRemove(lockDir);
|
|
128
|
+
return yield* atomicMkdir(lockDir);
|
|
129
|
+
}).pipe(Effect.ensuring(forceRemove(breakerPath)));
|
|
130
|
+
if (!recreated)
|
|
131
|
+
return yield* new NotAcquired();
|
|
132
|
+
}
|
|
133
|
+
// We own the lock dir — write heartbeat + meta with exclusive create
|
|
134
|
+
yield* exclusiveWrite(heartbeatPath, "", lockDir, "heartbeat already existed");
|
|
135
|
+
const metaJson = encodeMeta({ token, pid: process.pid, hostname, createdAt: new Date().toISOString() });
|
|
136
|
+
yield* exclusiveWrite(metaPath, metaJson, lockDir, "meta.json already existed");
|
|
137
|
+
return { token, metaPath, heartbeatPath, lockDir };
|
|
138
|
+
}).pipe(Effect.withSpan("EffectFlock.tryAcquire", {
|
|
139
|
+
attributes: { key },
|
|
140
|
+
}));
|
|
141
|
+
// -- retry wrapper (preserves Handle type) --
|
|
142
|
+
const acquireHandle = (lockfile, key, options) => tryAcquireLockDir(lockfile, key, options.staleMs).pipe(Effect.retry({
|
|
143
|
+
while: (err) => err._tag === "NotAcquired",
|
|
144
|
+
schedule: retrySchedule(options.timeoutMs),
|
|
145
|
+
}), Effect.catchTag("NotAcquired", () => Effect.fail(new LockTimeoutError({ key }))), Effect.timeoutOrElse({
|
|
146
|
+
duration: options.timeoutMs,
|
|
147
|
+
orElse: () => Effect.fail(new LockTimeoutError({ key })),
|
|
148
|
+
}));
|
|
149
|
+
// -- release --
|
|
150
|
+
const release = (handle) => Effect.gen(function* () {
|
|
151
|
+
const raw = yield* fs.readFileString(handle.metaPath).pipe(Effect.catch((err) => {
|
|
152
|
+
if (isPathGone(err))
|
|
153
|
+
return Effect.die(new ReleaseError({ detail: "metadata missing" }));
|
|
154
|
+
return Effect.die(err);
|
|
155
|
+
}));
|
|
156
|
+
const parsed = yield* Effect.try({
|
|
157
|
+
try: () => decodeMeta(raw),
|
|
158
|
+
catch: (cause) => new ReleaseError({ detail: "metadata invalid", cause }),
|
|
159
|
+
}).pipe(Effect.orDie);
|
|
160
|
+
if (parsed.token !== handle.token)
|
|
161
|
+
return yield* Effect.die(new ReleaseError({ detail: "token mismatch" }));
|
|
162
|
+
yield* forceRemove(handle.lockDir);
|
|
163
|
+
});
|
|
164
|
+
// -- build service --
|
|
165
|
+
const acquire = Effect.fn("EffectFlock.acquire")(function* (key, dir, options = {}) {
|
|
166
|
+
const lockDir = dir ?? lockRoot;
|
|
167
|
+
const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
|
|
168
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
169
|
+
yield* ensureDir(lockDir);
|
|
170
|
+
const lockfile = path.join(lockDir, Hash.fast(key) + ".lock");
|
|
171
|
+
// acquireRelease: acquire is uninterruptible, release is guaranteed
|
|
172
|
+
const handle = yield* Effect.acquireRelease(acquireHandle(lockfile, key, { staleMs, timeoutMs }), (handle) => release(handle));
|
|
173
|
+
// Heartbeat fiber — scoped, so it's interrupted before release runs
|
|
174
|
+
yield* Effect.suspend(() => {
|
|
175
|
+
const now = new Date();
|
|
176
|
+
return fs.utimes(handle.heartbeatPath, now, now);
|
|
177
|
+
}).pipe(Effect.ignore, Effect.repeat(Schedule.spaced(Math.max(100, Math.floor(staleMs / 3)))), Effect.forkScoped);
|
|
178
|
+
});
|
|
179
|
+
const withLock = Function.dual((args) => Effect.isEffect(args[0]), (body, key, dir) => Effect.scoped(Effect.gen(function* () {
|
|
180
|
+
yield* acquire(key, dir);
|
|
181
|
+
return yield* body;
|
|
182
|
+
})));
|
|
183
|
+
return Service.of({ acquire, withLock });
|
|
184
|
+
}));
|
|
185
|
+
EffectFlock.node = makeGlobalNode({ service: Service, layer: layer, deps: [Global.node, FSUtil.node] });
|
|
186
|
+
})(EffectFlock || (EffectFlock = {}));
|
package/dist/encode.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare function base64Encode(value: string): string;
|
|
2
|
+
export declare function base64Decode(value: string): string;
|
|
3
|
+
export declare function checksum(content: string): string | undefined;
|
|
4
|
+
export declare function sampledChecksum(content: string, limit?: number): string | undefined;
|