Code Monkey home page Code Monkey logo

effect's Introduction

Effect

Welcome to Effect, a powerful TypeScript framework that provides a fully-fledged functional effect system with a rich standard library.

Requirements

  • TypeScript 5.4 or newer
  • The strict flag enabled in your tsconfig.json file
{
  // ...
  "compilerOptions": {
    // ...
    "strict": true,
  }
}

Documentation

For detailed information and usage examples, please visit the Effect website.

Introduction to Effect

To get started with Effect, watch our introductory video on YouTube. This video provides an overview of Effect and its key features, making it a great starting point for newcomers:

Introduction to Effect

Connect with Our Community

Join our vibrant community on Discord to interact with fellow developers, ask questions, and share your experiences. Here's the invite link to our Discord server: Join Effect's Discord Community.

API Reference

For detailed information on the Effect API, please refer to our API Reference.

Pull Requests

We welcome contributions via pull requests! Here are some guidelines to help you get started:

  1. Fork the repository and clone it to your local machine.
  2. Create a new branch for your changes: git checkout -b my-new-feature.
  3. Ensure you have the required dependencies installed by running: pnpm install (assuming pnpm version 8.x).
  4. Make your desired changes and, if applicable, include tests to validate your modifications.
  5. Run the following commands to ensure the integrity of your changes:
    • pnpm codegen: Re-generate the package entrypoints in case you have changed the structure of a package or introduced a new module.
    • pnpm check: Verify that the code compiles.
    • pnpm test: Execute the tests.
    • pnpm circular: Confirm there are no circular imports.
    • pnpm lint: Check for code style adherence (if you happen to encounter any errors during this process, you can use pnpm lint-fix to automatically fix some of these style issues).
    • pnpm dtslint: Run type-level tests.
    • pnpm docgen: Check the integrity of the generated documentation.
  6. Create a changeset for your changes: before committing your changes, create a changeset to document the modifications. This helps in tracking and communicating the changes effectively. To create a changeset, run the following command: pnpm changeset. Always choose the patch option when prompted (please note that we are currently in pre-release mode).
  7. Commit your changes: after creating the changeset, commit your changes with a descriptive commit message: git commit -am 'Add some feature'.
  8. Push your changes to your fork: git push origin my-new-feature.
  9. Open a pull request against our main branch.

Pull Request Guidelines

  • Please make sure your changes are consistent with the project's existing style and conventions.
  • Please write clear commit messages and include a summary of your changes in the pull request description.
  • Please make sure all tests pass and add new tests as necessary.
  • If your change requires documentation, please update the relevant documentation.
  • Please be patient! We will do our best to review your pull request as soon as possible.

effect's People

Contributors

0x706b avatar ahrjarrett avatar alex-dixon avatar dependabot[bot] avatar federicobiccheddu avatar fubhy avatar gcanti avatar giacomoran avatar github-actions[bot] avatar imax153 avatar jessekelly881 avatar jjayet avatar khraksmamtsov avatar leonitousconforti avatar matheuspuel avatar mattiamanzati avatar mikearnaldi avatar nikgraf avatar patroza avatar pschyska avatar qlonik avatar r-cyr avatar suddenlygiovanni avatar sukovanej avatar thewilkybarkid avatar tim-smart avatar tylors avatar vecerek avatar wesselvdv avatar wmaurer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

effect's Issues

Design of HTTP client

Basic points:

  • support for all HTTP methods
  • works in browser and node
  • wraps response/request data in both success and error case
  • supports typed request/response
  • integrates with a generic tracing instrumentation
  • websocket?

Any ideas both on the API and on the features are open for discussion!

Proposals

To discuss ideas, any library you might think should have a wrapper or any ideas for improvements welcome!

Exit API

Exit lacks predicates and a fold

Organize Intro Call

Any day of next week would work for an intro call, I will provide a zoom invite to the interested.

Time proposals? I am in London so preferrably afternoon-evening UK time

Multitenant Logger

Implement a base logger using freeEnv and provide an implementation backed by winston

Implement Alt3E for effect

In order to not collide with existing 'alt' implementation (which is not 'alt' from 'Alt' Type Classe), I'll rename existing 'alt' to 'cond'

An in-range update of @matechs/effect is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye 👋 and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


The devDependency @matechs/effect was updated from undefined to 5.0.17.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@matechs/effect is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • build: There are 1 failures, 0 warnings, and 0 notices.

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

`nestedMap` benchmark is a bit misleading

The effect version is simply testing the performance of applying a pure increment function to a BigInt a thousand times, without any asynchronicity involved, due to the Pure escape hatch in the implementation. You can test this by writing either of the following:

const identity = (() => {
  const map = (v, f) => f(x)
  const pure = x => x
  return { map, pure }
})()

// Given an arbitrary `Apply`, produce an `Applicative`
// https://hackage.haskell.org/package/semigroupoids-5.3.4/docs/Data-Functor-Apply.html#t:MaybeApply
export const maybeApply = (F) => {
  const map = (fv, f) => (fv.tag === IPureTag ? new IPure(f(fv.a)) : F.map(fv, f));
  const pure = (v) => new IPure(v);
  const ap = (fv, ff) =>
    ff.tag === IPureTag
      ? map(fv, ff.a)
      : fv.tag === IPureTag
      ? F.map(ff, (f) => f(fv.a))
      : F.ap(fv, ff);

  return { map, pure, ap };
};

// Try for example maybeApply(QIO) or maybeApply(wave) or whatever

Both of these perform about the same as effect in the benchmark. In particular, maybeApply(F) will perform the same as effect regardless of what F is (I could write a really poorly performing asynchronicity abstraction and it would still "win" the benchmark if you wrapped it in maybeApply). In normal usage, the user's computation is going to have at least one actual asynchronous step that they then map/chain transformations over (otherwise they wouldn't be representing it as an asynchronous effect in the first place).

If the initial T.pure(BigInt(0)) is replaced with T.asyncTotal(cb => { cb(BigInt(0)); return () => {}; }) (which is the simplest way I could figure out to work out the performance of actually mapping over an asynchronous effect) and corresponding changes are made to the other benchmarks, the fastest implementation (at least on my system) turns out to be QIO. effect's performance is roughly halved compared to the T.pure version, although it still retains a significant lead over wave.


If you want to try this out yourself, here's the typical result I was observing by running yarn ts-node -T bench/nestedMap.ts:

yarn run v1.21.1
$ /mnt/code/git/js/experiments/mapbenchmark/matechs-effect/node_modules/.bin/ts-node -T bench/nestedMap.ts
effect x 18,743 ops/sec ±0.96% (84 runs sampled)
wave x 5,964 ops/sec ±1.35% (86 runs sampled)
qio x 11,439 ops/sec ±1.53% (86 runs sampled)
Fastest is effect
Done in 18.26s.

Here's the changes I made:

diff --git a/packages/effect/bench/nestedMap.ts b/packages/effect/bench/nestedMap.ts
index 8c5b3a92..ba896fde 100644
--- a/packages/effect/bench/nestedMap.ts
+++ b/packages/effect/bench/nestedMap.ts
@@ -8,7 +8,10 @@ const MAX = 1e3;
 const inc = (_: bigint) => _ + BigInt(1);
 
 export const nestedMapWave = (): wave.Wave<never, bigint> => {
-  let io: wave.Wave<never, bigint> = wave.pure(BigInt(0));
+  let io: wave.Wave<never, bigint> = wave.asyncTotal((cb) => {
+    cb(BigInt(0));
+    return () => {};
+  });
   for (let i = 0; i < MAX; i++) {
     io = wave.map(io, inc);
   }
@@ -16,15 +19,18 @@ export const nestedMapWave = (): wave.Wave<never, bigint> => {
 };
 
 export const nestedMapQio = (): QIO<bigint> => {
-  let io: QIO<bigint> = QIO.resolve(BigInt(0));
+  let io: QIO<bigint> = QIO.uninterruptible((cb) => cb(BigInt(0)));
   for (let i = 0; i < MAX; i++) {
     io = QIO.map(io, inc);
   }
   return io;
 };
 
-export const nestedMapEffect = (): T.Sync<bigint> => {
-  let io: T.Sync<bigint> = T.pure(BigInt(0));
+export const nestedMapEffect = (): T.Async<bigint> => {
+  let io: T.Async<bigint> = T.asyncTotal((cb) => {
+    cb(BigInt(0));
+    return () => {};
+  });
   for (let i = 0; i < MAX; i++) {
     io = T.effect.map(io, inc);
   }

And here's the typical result I see afterwards:

yarn run v1.21.1
$ /mnt/code/git/js/experiments/mapbenchmark/matechs-effect/node_modules/.bin/ts-node -T bench/nestedMap.ts
effect x 9,452 ops/sec ±1.54% (79 runs sampled)
wave x 5,984 ops/sec ±0.98% (86 runs sampled)
qio x 11,491 ops/sec ±1.27% (86 runs sampled)
Fastest is qio
Done in 18.26s.

I'm not sure what the "simplest" way to turn an arbitrary callback based asynchronous computation into an effect or wave is, if it's not asyncTotal (and hence the updated benchmark is not fair) please let me know.

Conventions

To be addressed in branch conventions, convert base effect and usages to respect fp-ts standards for curried functions (see option)

provideSomeM does not remove provided environements

this example work correctly

import * as EFF from '@matechs/effect/lib/effect'

type EnvFromEffect<T> = T extends EFF.Effect<infer R, infer E, infer A> ? R : never;

const provideB = EFF.provideSomeM(EFF.pure({b: 10}));

const needAB = EFF.access((env: {a: number} & {b: number}) => env.a)

const needOnlyA = provideB(needAB)

/**
 * type EnvForNeedOnlyA = {
 *  a: number;
 * } 
 */
type EnvForNeedOnlyA = EnvFromEffect<typeof needOnlyA> 

but if we want to access to environment like EFF.accesss((env: {a: number, b:number}) => env.a) function provideB does not remove dependency to b.

const needAB2 = EFF.access((env: {a:number, b: number}) => env.a)

const needOnlyA2 = provideB(needAB2)

/**
 * type EnvForNeedOnlyA2 {
 *  a: number;
 *  b: number;
 * }
 */
type EnvForNeedOnlyA2 = EnvFromEffect<typeof needOnlyA2> 

I have a solution to this problem but I don't know if it's the best and elegant way.

the solution that I came up with (I just change the types):

import * as EFF from "@matechs/effect/lib/effect";

function chain_<R, E, A, R2, E2, B>(
  inner: EFF.Effect<R, E, A>,
  bind: FunctionN<[A], EFF.Effect<R2, E2, B>>
): EFF.Effect<R & R2, E | E2, B> {
  return new EFF.EffectIO(EFF.EffectTag.Chain, inner, bind) as any;
}

export const provideSomeM = <R2, R, E2>(f: EFF.Effect<R2, E2, R>) => <
  T,
  R3 = T extends EFF.Effect<infer R4, infer __, infer ___>
    ? Omit<R4, keyof R>
    : never,
  E = T extends EFF.Effect<R3 & R, infer EE, infer ____> ? EE : never,
  A = T extends EFF.Effect<R3 & R, E, infer AE> ? AE : never
>(
  ma: T extends EFF.Effect<R3 & R, E, A> ? T : never
): EFF.Effect<R3 & R2, E | E2, A> => chain_(f, r => EFF.provide(r)(ma));


const provideB2 = provideSomeM(EFF.pure({b: 10}));

const needOnlyA3 = provideB2(needAB2)

/**
 * type EnvForNeedOnlyA2 {
 *  a: number;
 * }
 */
type EnvForNeedOnlyA3= EnvFromEffect<typeof needOnlyA3> 

the main thing that I changed is the declaration of this function

export const provideSomeM = <R2, R, E2>(f: EFF.Effect<R2, E2, R>) => <
  T,
  R3 = T extends EFF.Effect<infer R4, infer __, infer ___>
    ? Omit<R4, keyof R>
    : never,
  E = T extends EFF.Effect<R3 & R, infer EE, infer ____> ? EE : never,
  A = T extends EFF.Effect<R3 & R, E, infer AE> ? AE : never
>(
  ma: T extends EFF.Effect<R3 & R, E, A> ? T : never
): EFF.Effect<R3 & R2, E | E2, A> => chain_(f, r => EFF.provide(r)(ma));

I think there is other provider function that has this problem like provide and provideSM

An in-range update of io-ts is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye 👋 and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


The devDependency io-ts was updated from 2.1.2 to 2.1.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

io-ts is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • build: There are 2 failures, 0 warnings, and 0 notices.

Release Notes for 2.1.3
  • Polish
    • remove useless hasOwnProperty calls, closes #423 (@gcanti)
Commits

The new version differs by 1 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

How to cancel requests that occur too often?

Hi.
Thanks for your huge work at fp-stylish effects.
I haven't enough experience with it. But conception looks very promising.

Library has rich api, but I haven't realize how to solve such case:
I have suggest input. Every time when I type in it, it emits onChange event with 300ms debounce.
I triggers requests to backend. But BE answer with unpredictable speed with 100-500ms.
That's why our data can stale. To prevent this we can make singletone conditional var, but it looks awkward.

How to deal with in fp style?

HTTP fetch implementation, tries to parse json even on 204 response

  • while using e.g H.patch while providing the fetch implementation for HTTP client
  • if the server responds with Content-Type: application/json
  • and the server responds with 204 Empty Response
  • the http fetch client still tries to decode the body via .json() and fails with FetchError: invalid json response body at ... reason: Unexpected end of JSON input

Workaround:
const patch = H.request("PATCH", "JSON", "TEXT") and use that instead.

Expected:
a 204 response would result in void body.

Discuss Representation of Cancellability

For reference, the current signature of an Async is
FunctionN<[FunctionN<[Either<E, A>], void>], Lazy<void>
which for simplicity I shall reproduce in HM as
(Either e a -> Unit) -> (Unit -> Unit)
for less noise.

The return is a callback that invokes cancellation.
This is unsatisfying for several reasons.
Chief among them is that the uninterruptible combinator exists to bracket effects that shouldn't be cancelled for semantic reasons or resource safety.
However, there is at least a class of effects (see node fs module operations) that are inherently uninterruptible.
Forcing users to be aware of the nuances of cancelation is likely error prone.

Additionally, this model fails to capture cases where cancelation itself might fail or take some time to complete.
In these cases we are potentially allowing the dispatch loop to advance before an effect is truly complete which has implications for semantics.

I was recently doing some research and I came across the cancelation signature for purescript-aff which has an interesting signature.
The cancellation signature in Aff (given at https://github.com/purescript-contrib/purescript-aff/blob/master/src/Effect/Aff/Compat.purs#L21) is
newtype EffectFnCanceler = EffectFnCanceler (EffectFn3 Error (EffectFnCb Error) (EffectFnCb Unit) Unit)
Which translates roughly to Error -> (Error -> Unit) -> (Unit -> Unit) -> Unit
I.e. a canceler receives the interrupt error and a callback for cancelation succeeded and cancelation failed.

Something similar would improve the expression power of Async.
Delayed interruption is expressable via the callbacks and inherent uninterruptibility can be expressed by providing a cancel function that declines to invoke callbacks.
In this case, the driver would resume via normal completion, check the interruption flag as it does at event boundaries and take action there.
No need for remembering uninterruptible when wrapping node fs for instance.

This may need to be a breaking change to the API if only because of the semantics change might be confusing otherwise.
While it might be possible to maintain backwards compatibility by making the current Async delegate to the enhanced async such that cancellation is assumed synchronous and safe this is probably not the best strategy.
Certainly the type of the Effect union would change which is breaking anyway so might as well go all the way.
The impact is probably most commonly felt at integration anyway, user code mostly wouldn't need to change barring assumption that it makes around how fast cancelation completes.

Http module to support binary fetching

Currently the Http Module has built-in support for text and json deserialization. It would be great to support binary fetching too, such that it can be used to download audio and video.

I suggest we basically "Deserialize" to Base64

effect does not merge environments on sequenceS

let's say we have this code

import * as EFF from '@matechs/effect/lib/effect';
import {sequenceS} from 'fp-ts/lib/Apply'

const seqSeffect = sequenceS(EFF.effect)

const firstEffect = () => EFF.accessM(({a}: {a: number}) => EFF.pure(a))
const secondEffect = () => EFF.accessM(({b}: {b: number}) => EFF.pure(b) )

seqSeffect({first: firstEffect(), second: secondEffect()})

this will raise this error

Type 'Effect<{ b: number; }, never, number>' is not assignable to type 'Effect<{ a: number; }, never, any>'.
  Property 'a' is missing in type '{ b: number; }' but required in type '{ a: number; }

Consider making `take`, `drop`, ... curried on streams

Hi and thanks for sharing this library, it looks awesome ...

I was giving it a try and found that stream.take function (and others) take 2 arguments, so id doesn't look too nice with pipe:

import { effect as T, stream as S } from "@matechs/effect"
import { pipe } from "fp-ts/lib/pipeable"

pipe(
  S.periodically(100),
  S.chain(n => S.encaseEffect(T.pure(n))),
  s => S.take(s, 100) // -> S.take(100)
)

Did you consider changing signature to (n: number) => <S>(stream: S) => ...? If so - what are the drawbacks of doing so?

Thanks!

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet.
We recommend using:

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

Remove all Symbol from URIs

Symbol uris are nice but don't play well with es6 and in general dynamic loading where with loaders end up being duplicated.

Debugging errors out of symbolic references is also tricky.

We can have uniqueness by namespacing URIs like @matechs/effect/freeEnv/specURI

retry-ts should be listed as dependency or peer dependency

I upgraded @matechs/effect to 2.0.3. And my build failed with

ERROR in ./node_modules/@matechs/effect/es6/retry.js
Module not found: Error: Can't resolve 'retry-ts' in '/home/runner/work/typescript-react-starter/typescript-react-starter/node_modules/@matechs/effect/es6'
 @ ./node_modules/@matechs/effect/es6/retry.js 3:0-59 5:22-33 12:14-32
 @ ./node_modules/@matechs/effect/es6/index.js
 @ ./src/index.tsx

After installing retry-ts, my next build succeeded.
retry-ts should then be listed as dependency or at least peer dependency to warn when installing.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.