Why does akka http not continue requesting? - request

I've got an issue with akka-http. I'm trying to request several times in a flow but it stops with default configuration at 4 times. Here is the code I use. Can someone help me understanding why it waits?
Thanks a lot
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.{HostConnectionPool, OutgoingConnection}
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.stream._
import akka.stream.scaladsl._
import com.typesafe.scalalogging.LazyLogging
import scala.concurrent.Future
import scala.util.{Try, Failure, Success}
object TestHttp extends LazyLogging {
def main(args: Array[String]) {
implicit val system = ActorSystem()
import system.dispatcher
val decider: Supervision.Decider = {
case e => {
logger.error(e.getMessage, e)
Supervision.Resume
}
}
implicit val materializer = ActorMaterializer(ActorMaterializerSettings(system).withSupervisionStrategy(decider).withDebugLogging(true))
val resultSink: Sink[(Try[HttpResponse], Int), Future[Unit]] = Sink.foreach { case (hr, i) => {
hr match {
case Success(r) => logger.info(s"Success ${r} for ${i}")
case Failure(e) => logger.error(s"Error ${e} for ${i}")
}
}
}
val source: Source[Int, Unit] = Source(0 to 1500).map(i => {
logger.info(s"${i} iteration")
i
})
val buildHr: Flow[Int, (HttpRequest, Int), Unit] = Flow[Int].map { case s => {
(HttpRequest(uri = "/").withDefaultHeaders(), s)
}
}
val connection: Flow[(HttpRequest, Int), (Try[HttpResponse], Int), HostConnectionPool] = Http().cachedHostConnectionPool("www.adajam.uk.com")
import FlowGraph.Implicits._
source.via(buildHr).via(connection).to(resultSink).run()
}
}

In order to release the connection, the body has to be read.
This can be done with
r.entity.dataBytes.to(Sink.ignore)

Related

Property 'items' does not exist on type '[]'?

So I am working on this project to learn typescript and I don't know how to solve it so I came here if somebody can explain what is an error and how to fix I would be grateful for the rest of my life :D
context.tsx
import React, {createContext,ReactNode,ReactPortal,useState} from 'react'
import axios from 'axios'
import { AnyMxRecord } from 'dns';
import database from '../database';
import { string } from 'yargs';
const top250Movies = createContext<[]>([
]);
const MoviesContext: React.FC<any> = ({children}) => {
const [top250 , setTop250 ] = useState<any>('');
if(top250 == ''){
setTop250(database);
}
return (
<top250Movies.Provider value={top250}>{children}</top250Movies.Provider>
)
}
export default MoviesContext
export { top250Movies}
Homepage.tsx
import React, { useContext } from 'react'
import { top250Movies } from '../context/context'
import Footer from '../layouts/Footer'
import Navbar from '../layouts/Navbar'
import '../styles/Homepage.css'
function Homepage() {
let backendData = useContext(top250Movies);
if(backendData !== null){
if(Array.isArray(backendData)){
console.log(backendData.items.map((item: any) =>{ return item}));
}
}
return (
<div className='Homepage'><Navbar/> <div className="Homepage-content">Homepage</div> <Footer/></div>
)
}
export default Homepage
Expected output from backend data is object that in it has an object with array of movies e.g. backendData:{titles:[array]}
backendData is an array you can map() directly on it !
if(backendData !== null){
if(Array.isArray(backendData)){
console.log(backendData.map((item: any) =>{ return item}));
}
}

React - useEffect based on service variable

I have a question about usage of React.useEffect function based on the variable being a part of a service which I use to make some magic behind.
import React, { useEffect } from "react";
import { treeStructureService } from "../../services/dependency_injection";
import "./ModelTree.css";
const ModelTree = (props: any) => {
useEffect(() => {
// some code
console.log('Use Effect runs...')
}, [treeStructureService.tree])
return <div>ModelTree</div>;
};
export { ModelTree };
TreeStructureService.tree changes the variable depending upon the upload of new files to a project. Such action takes some time in the background, which is why I tried to use such a variable in useEffect to rerender the tree again when changes were propagated to the service.
The most interesting part of the TreeStructureService was presented below:
import { TreeNode } from "../../interfaces/tree_node";
import { modelLoaderService } from "../dependency_injection";
export class TreeStructureService {
public tree: TreeNode | undefined;
constructor() {}
async addTreeToProject(modelID: number, newTree: TreeNode):Promise<void> {
if (modelID == 0) {
this.tree = newTree;
}else{
console.log('Doing magic')
}
}
}
In dependency injection, necessary services are called and exported to use the "equivalent" of DependencyInjection from Angular.:
import { IFCLoaderService } from "./viewer/model_loaders/ifc_loader_service";
import { ModelLoaderService } from "./viewer/model_loaders/model_loader_service";
import { SelectionService } from "./viewer/selection_service";
import { ThreeSceneService } from "./viewer/three_scene_service";
import { TreeStructureService } from "./viewer/tree_structure_service";
import { VisibilityService } from "./viewer/visiblity_service";
export const modelLoaderService = new ModelLoaderService();
export const ifcLoaderService = new IFCLoaderService();
export const threeSceneService = new ThreeSceneService();
export const selectionService = new SelectionService();
export const visibilityService = new VisibilityService();
export const treeStructureService = new TreeStructureService();
I'll be glad for any suggestions. In the next steps, I'll add redux to control the state of the application. So maybe you have some idea that I could pass a new tree as an action argument? However, I don't know how to do it outside of the components.
While you don't need any fancy code to connect your tree model to React, there a few ways to do that.
Basically, you have to wire or connect your state changes.
You could write your own event emmitter, then subscribe via react hook, but here is straightforward shortcut. Mobx does this for you
import React, { useEffect } from "react"
import { treeStructureService } from "../../services/dependency_injection"
import "./ModelTree.css"
import { TreeNode } from "../../interfaces/tree_node"
import { modelLoaderService } from "../dependency_injection"
// Step 1: Notice 2 new imports
import { makeAutoObservable } from "mobx"
import { observer } from "mobx-react-lite"
export class TreeStructureService {
public tree: TreeNode | undefined
constructor() {
// Step 2: notice that I mark `tree` as observable
makeAutoObservable(this)
}
async addTreeToProject(modelID: number, newTree: TreeNode): Promise<void> {
if (modelID == 0) {
this.tree = newTree
} else {
console.log("Doing magic")
}
}
}
// Step 3: Notice the observer wrapper from "mobx-react-lite"
export const ModelTree = observer((props: any) => {
// This re-render when TreeNode changes
console.log(treeStructureService.tree)
return <div>ModelTree</div>
})

extended Selector Function with fs

I try to write an own Selector that will read an XML and get an XPath from it. But my idea does not work any suggestion?
I use
//xpath.js
import { Selector } from 'testcafe';
import fs from "fs";
import downloadsFolder from "downloads-folder";
import {DOMParser} from 'xmldom'
const elementByXPath = Selector(xpath => {
const items = [];
var xml = fs.readFileSync(downloadsFolder()+'export.xml', 'utf8').toString();
var doc = new DOMParser().parseFromString(xml);
//for debug reson
console.log(xml);
/*
Logik for XPath here
*/
items.push('0');
return items;
});
export default function (xpath) {
return Selector(elementByXPath(xpath));
}
and the fixture is
//testfixture.js
import { Selector } from 'testcafe';
import XPathSelector from './xpath';
fixture `SM Run 1`
test('Per Anhalter durch die Galaxies', async t => {
await t
.navigateTo("http://www.ifoerster.com")
await t
.expect(elementByXPath('test')).eql(1)
console.log("Fertig")
});
In my understanding, this has to work.

IO consuming with FP-TS

What is the idiomatic fp alternative of forEach part in this code
const ios: IO<void>[] = [...]
ios.forEach(io => io());
?
There are some docs which use sequence_ from Foldable but it is no longer available in fp-ts#2.0.3.
EDIT:
The best I could do is
import { array } from 'fp-ts/lib/Array';
array.sequence(io)(ios)();
but sequence collects the results and I do not really have anything to do with void[].
I was wondering the same thing. The following seems to work.
import { IO, io } from 'fp-ts/lib/IO';
import { traverse_ } from 'fp-ts/lib/Foldable';
import { array } from 'fp-ts/lib/Array';
import { identity } from 'fp-ts/lib/function';
import { log } from 'fp-ts/lib/Console';
const actions: Array<IO<void>> = [log('hello'), log('world')];
const action: IO<void> = traverse_(io,array)(actions,identity);

How to extract kotlin-react html into a method

I'd like to create a method containing an "html" snippet but I get the error below.
import react.dom.a
import react.dom.button
import react.dom.div
import react.dom.nav
import react.dom.span
import kotlinx.html.ButtonType
import react.RBuilder
import react.RComponent
import react.RProps
import react.RState
class App : RComponent<RProps, RState>() {
override fun RBuilder.render() {
div("container fill") {
}
div {
content()
}
}
fun content() {
return div() { } // the error below is for this line
}
}
error: unresolved reference. None of the following candidates is
applicable because of receiver type mismatch: public inline fun
RBuilder.div(classes: String? = ..., block: RDOMBuilder.() ->
Unit): ReactElement defined in react.dom
return div() {
Any ideas?
You should add the receiver, and probably get rid of return like this:
class App : RComponent<RProps, RState>() {
override fun RBuilder.render() {
div("container fill") {
}
div {
content()
}
}
fun RBuilder.content() {
div() { }
}
}

Resources