kontraktor_client 0.0.4

  • Readme
  • Changelog
  • Example
  • Installing
  • 44

Long-Poll client for http/json published kontraktor actors #

example Server ´´´java

import org.nustaq.kontraktor.; import org.nustaq.kontraktor.annotations.CallerSideMethod; import org.nustaq.kontraktor.annotations.Local; import org.nustaq.kontraktor.apputil.; import org.nustaq.kontraktor.impl.SimpleScheduler; import org.nustaq.kontraktor.remoting.encoding.Coding; import org.nustaq.kontraktor.remoting.encoding.SerializerType; import org.nustaq.kontraktor.remoting.http.undertow.Http4K; import org.nustaq.kontraktor.services.rlclient.DataClient; import org.nustaq.kontraktor.webapp.javascript.clojure.ClojureJSPostProcessor; import org.nustaq.kontraktor.webapp.transpiler.JSXIntrinsicTranspiler; import org.nustaq.reallive.messages.*; import org.nustaq.reallive.records.MapRecord;

import java.io.File; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream;

public class ExampleServer extends Actor

public static ExampleServerConfig cfg;

// threads to dispatch session onto
private Scheduler clientThreads[];
private Random rand = new Random();
private ExampleServerService service;
private DataClient dclient;

@Local
public void init(String args[]) {
    clientThreads = new Scheduler[cfg.getNumSessionThreads()];
    IntStream.range(0,cfg.getNumSessionThreads())
        .forEach( i -> clientThreads[i] = new SimpleScheduler(10000, true /*Important!*/ ));
    service = ExampleServerService.start(args);
    service.setWebServer(self());
    dclient = service.getDClient();
}

@CallerSideMethod
public DataClient getDClient() {
    return getActor().dclient;
}

public IPromise test( String arg0 ) {
    return resolve("hello "+arg0);
}

public IPromise test1( String arg0, Callback cb ) {
    delayed(1000, () -> cb.pipe(arg0+" ->1"));
    delayed(2000, () -> cb.pipe(arg0+" ->2"));
    delayed(3000, () -> cb.complete());
    return resolve("hello callback "+arg0);
}

////////////////////// Session handling //////////////////////////////////////////////

public IPromise login(String email, String pwd, Callback events ) {
    if ( "".equals(email.trim()) ) {
        return reject("empty email");
    }
    Promise p = new Promise();
    getDClient().tbl(UserTableName).get(email.toLowerCase()).then( (r,e) -> {
        if ( r != null ) {
            UserRecord user = new UserRecord(r);
            if ( pwd.equals(user.getPwd()) ) {
                ExampleSession session = AsActor(
                    ExampleSession.class,
                    // randomly distribute session actors among clientThreads
                    clientThreads[rand.nextInt(clientThreads.length)]
                );
                session.init(user,self(),events);
                p.resolve(new LoginData().session(session).user(user)); // == new Promise(session)
            } else {
                p.reject("wrong user or password");
            }
        } else {
            p.reject("wrong user or password");
        }
    });
    return p;
}
///////////////////// config and startup ////////////////////////////////////////////

public static void main(String[] args) throws InterruptedException {

    if ( ! new File("./src/main/web/index.html").exists() ) {
        System.out.println("Please run with project working dir");
        System.exit(-1);
    }

    // separate&remove for distributed / clustered setup
    ExampleDataClusterStartup.main(new String[0]);

    ExampleServerConfig cfg = ExampleServerConfig.read("./run/etc/config.kson");
    ExampleServer.cfg = cfg;

    ExampleServer app = AsActor(ExampleServer.class);
    app.init(new String[] { "-sp", ""+5678, "-monitorport", "8082" } /*args*/);

    Mailer.DEBUG_MAIL = cfg.isDevMode();
    try {
        MailCfg mc = MailCfg.read("./run/etc/mailcfg.kson");
        Mailer.initSingleton( mc,cfg.publicUrl );
    } catch (Exception e) {
        e.printStackTrace();
        Mailer.initSingleton( new MailCfg(),cfg.publicUrl );
    }

    Class CLAZZES[] = {
        LoginData.class,
        SessionEvent.class,
    };

    Http4K.Build(cfg.getBindIp(), cfg.getBindPort())
        .fileRoot( "imgupload","./run/upload/image")
        .fileRoot( "img","./run/data/img")
        .httpAPI("/api", app) // could also be websocket based (see IntrinsicReactJSX github project)
            .coding(new Coding(SerializerType.JsonNoRef, CLAZZES))
            .setSessionTimeout(TimeUnit.MINUTES.toMillis(cfg.getSessionTimeoutMinutes() ))
            .buildHttpApi()
        .build();

}

}

0.0.1

  • initial checkin. basic stuff works, expect quirky error handling and hickups in decoding java-serializatoin-style json

0.0.2

  • minor fixes

0.0.3

  • isDisconnected method

example/example.dart

import '../lib/kontraktor-client.dart';

void main() async {
  KontraktorConnection con = KontraktorConnection("http://localhost:8087/api");
  await con.connect();
  print( "res0 "+await con.ask("test", ["pokpok"]) );
  print( "res1 "+await con.ask("test", ["pokpok1"]) );
  print( "res2 "+await con.ask("test", ["pokpok2"]) );

  print( "test2 "+await con.ask("test1",
    [
      "pokpok2",
      (res,e) {
        print("cb test2 $res $e");
      }
    ]
  )
  );
  var login = await con.ask("login", ["xx@xx.xx","qweqwe", (res,err) async {
    print( "Session CB received:$res $err" );
  }]);
  var sess = login["session"];
  String res1 = await sess.ask( "hello", ["pokpok"] );
  print( "res: $res1" );

  print( con.sid );
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  kontraktor_client: ^0.0.4

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:kontraktor_client/kontraktor-client.dart';
import 'package:kontraktor_client/kontraktor-server-playground.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
0
Health:
Code health derived from static analysis. [more]
86
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
44
Learn more about scoring.

We analyzed this package on Feb 27, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.5

Health issues and suggestions

Document public APIs. (-0.61 points)

75 out of 76 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Fix lib/kontraktor-client.dart. (-12.22 points)

Analysis of lib/kontraktor-client.dart reported 26 hints, including:

line 62 col 19: DO use curly braces for all flow control structures.

line 64 col 19: DO use curly braces for all flow control structures.

line 66 col 19: DO use curly braces for all flow control structures.

line 70 col 19: DO use curly braces for all flow control structures.

line 80 col 12: Use isNotEmpty instead of length

Fix lib/kontraktor-server-playground.dart. (-1.49 points)

Analysis of lib/kontraktor-server-playground.dart reported 3 hints:

line 30 col 14: Use isNotEmpty instead of length

line 38 col 11: Future results in async function bodies must be awaited or marked unawaited using package:pedantic.

line 42 col 9: Future results in async function bodies must be awaited or marked unawaited using package:pedantic.

Maintenance suggestions

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.0 <3.0.0
http ^0.12.0+2 0.12.0+4
uuid ^2.0.4 2.0.4
Transitive dependencies
async 2.4.0
charcode 1.1.3
collection 1.14.12
convert 2.1.1
crypto 2.1.4
http_parser 3.1.3
meta 1.1.8
path 1.6.4
pedantic 1.9.0
source_span 1.6.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6