GithubHelp home page GithubHelp logo

mbrukman / docs Goto Github PK

View Code? Open in Web Editor NEW

This project forked from logux/docs

0.0 1.0 0.0 564 KB

Guide, recipes, and protocol specifications for Logux

Home Page: https://logux.io/

License: MIT License

JavaScript 100.00%

docs's Introduction

Logux

Logux and WebSocket client/server framework to make:

  • Collaborative apps when multiple users work with the same document. Logux has features inspired by CRDT to resolve edit conflicts between users. Real-time updates to prevent conflicts. Time travel to keep actions order the same on every client. A distributed timer to detect the latest changes.
  • Real-time to see changes by another user immediately. Logux combines WebSocket with modern reactive client architecture. It synchronizes Redux actions between clients and servers, and keeps the same order of actions.
  • Optimistic UI to improve UI performance by updating UI without waiting for an answer from the server. Time travel will revert changes later if the server refuses them.
  • Offline-first for the next billion users or New York City Subway. Logux saves Redux actions to IndexedDB and has a lot of features to merge changes from different users.
  • Compatible with modern stack: Redux and pure JS API, works with any back-end language and any database.
  • Just extra 9 KB in client-side JS bundle.

Ask your questions at community chat or commercial support.

Next chapter

Sponsored by Evil Martians

Client Example

React/Redux client

Using Logux Redux:

export const Counter = () => {
  const counter = useSelector(state => state.counter)
  const dispatch = useDispatch()
  // Load current counter from server and subscribe to counter changes
  const isSubscribing = useSubscription(['counter'])
  if (isSubscribing) {
    return <Loader></Loader>
  } else {
    // dispatch.sync() will send Redux action to all clients
    return <div>
      <h1>{ counter }</h1>
      <button onClick={ dispatch.sync({ type: 'INC' }) }>
    </div>
  }
}
Pure JS client

You can use Logux Client API with any framework:

log.on('add', (action, meta) => {
  if (action.type === 'INC') {
    counter.innerHTML = parseInt(counter.innerHTML) + 1
  }
})

increase.addEventListener('click', () => {
  log.add({ type: 'INC' }, { sync: true })
})

loading.classList.add('is-show')
log
  .add({ type: 'logux/subscribe' channel: 'counter' }, { sync: true })
  .then(meta => {
    const unbind = log.on('add', action => {
      if (action.type === 'logux/processed' && action.id === meta.id) {
        loading.classList.remove('is-show')
        unbind()
      }
    })
  })

Server Example

Node.js

Using Logux Server:

server.channel('counter', {
  access () {
    // Access control is mandatory. API was designed to make it harder to write dangerous code.
    return true
  },
  async init (ctx) {
    // Load initial state when client subscribing to the channel.
    // You can use any database.
    let value = await db.get('counter')
    ctx.sendBack({ type: 'INC', value })
  }
})

server.type('INC', {
  resend () {
    return { channel: 'counter' }
  },
  access () {
    return true
  },
  async process () {
    // Don’t forget to keep action atomic
    await db.set('counter', 'value += 1')
  }
})
Ruby on Rails

logux_rails gem with the Logux WebSocket proxy server.

# app/logux/channels/counter.rb
module Channels
  class Counter < Logux::ChannelController
    def initial_data
      [{ type: 'INC', value: db.counter }]
    end
  end
end
# app/logux/actions/inc.rb
module Actions
  class Inc < Logux::ActionController
    def inc
      # Don’t forget to keep action atomic
      db.update_counter! 'value += 1'
    end
  end
end
# app/logux/policies/channels/counter.rb
module Policies
  module Channels
    class Counter < Policies::Base
      # Access control is mandatory. API was designed to make it harder to write dangerous code.
      def subscribe?
        true
      end
    end
  end
end
# app/logux/policies/actions/inc.rb
module Policies
  module Actions
    class inc < Policies::Base
      def inc?
        true
      end
    end
  end
end
Any other HTTP server

You can use any HTTP server with Logux WebSocket proxy server. Here is a PHP-like pseudocode example:

<?php
$req = json_decode(file_get_contents('php://input'), true);
if ($req['password'] == LOGUX_PASSWORD) {
  foreach ($req['commands'] as $command) {
    if ($command[0] == 'action') {
      $action = $command[1];
      $meta = $command[2];

      if ($action['type'] == 'logux/subscribe') {
        echo '[["approved"],';
        $value = $db->getCounter();
        send_json_http_post(LOGUX_HOST, [
          'password' => LOGUX_PASSWORD,
          'version' => 1,
          'commands' => [
            [
              'action',
              ['type' => 'INC', 'value' => $value],
              ['clients' => get_client_id($meta['id'])]
            ]
          ]
        ]);
        echo '["processed"]]';

      } elseif ($action['type'] == 'inc') {
        $db->updateCounter('value += 1');
        echo '[["approved"],["processed"]]';
      }
    }
  }
}

Talks

CRDT ideas in Logux

Youtube:c7t_YBNHkeo CRDT ideas in Logux talk

Using Logux in Production

Youtube:DvHNOplQ-tY Using Logux in Production talk

docs's People

Watchers

 avatar

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.