code
stringlengths
1
1.05M
repo_name
stringlengths
7
65
path
stringlengths
2
255
language
stringclasses
236 values
license
stringclasses
24 values
size
int64
1
1.05M
package com.study.aio.client; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.CountDownLatch; /** * Created by wusz on 2018/5/17. */ public class AsyncTimeClientHandler implements Runnable,CompletionHandler<Void,AsyncTimeClientHandler> { private String host; private int port; AsynchronousSocketChannel client; CountDownLatch latch; public AsyncTimeClientHandler(String host, int port) { this.host = host; this.port = port; try { client = AsynchronousSocketChannel.open(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { latch = new CountDownLatch(1); client.connect(new InetSocketAddress(host,port),this,this); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } try { client.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public void completed(Void result, AsyncTimeClientHandler attachment) { byte[] req = "QUERY TIME ORDER".getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(req.length); writeBuffer.put(req); writeBuffer.flip(); client.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result, ByteBuffer buffer) { if(buffer.hasRemaining()) { client.write(buffer,buffer,this); } else { ByteBuffer readBuffer = ByteBuffer.allocate(1024); client.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result, ByteBuffer buffer) { buffer.flip(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); try { String body = new String(bytes, "UTF-8"); System.out.println("Now is : " + body); latch.countDown(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { try { client.close(); latch.countDown(); } catch (IOException e) { e.printStackTrace(); } } }); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { try { client.close(); latch.countDown(); } catch (IOException e) { e.printStackTrace(); } } }); } @Override public void failed(Throwable exc, AsyncTimeClientHandler attachment) { } }
vincentjava/netty-study
src/main/java/com/study/aio/client/AsyncTimeClientHandler.java
Java
apache-2.0
3,563
package com.study.aio.client; /** * @description: * @author: wusz * @date: 2018/6/12 */ public class Demo1 { }
vincentjava/netty-study
src/main/java/com/study/aio/client/Demo1.java
Java
apache-2.0
116
package com.study.aio.client; import org.apache.commons.lang3.StringUtils; import java.io.*; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Created by wusz on 2018/5/17. */ public class Test implements Serializable { public String s = "hello"; public static final long serialVersionUID = -4841994837142898086L; private List<String> list = new ArrayList<>(); /* stash测试 */ public static void main(String[] args) throws UnsupportedEncodingException, ParseException { // testLatch(); // bigDecimal(); // Date date = new Date(); // System.out.println(System.currentTimeMillis()); // long l = System.currentTimeMillis(); // Date date = new Date(l); // Date date1 = new Date(l); // System.out.println(date.equals(date1)); // String tom = new String("Tom"); // System.out.println(tom); // serialize(); // fun(); /*Test t1 = new Test(); Test t2 = new Test(); System.out.println(t1.equals(t2)); List<Test> list = Arrays.asList(t1); boolean c = list.contains(t2); System.out.println(c); System.out.println(((Test)null).serialVersionUID);*/ // try { // int i = 1 / 0; // } finally { // System.out.println("end"); // } // System.out.println("-----"+System.getProperty("line.separator")+"------"); /*ByteBuffer byteBuffer = ByteBuffer.allocate(1024); byteBuffer.putInt(3); byteBuffer.position(0); byteBuffer.put("hello".getBytes()); byteBuffer.flip(); byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); System.out.println(new String(bytes,"UTF-8"));*/ /* List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 3L)); list.remove(5L); System.out.println(list);*/ /*List<String> list = Arrays.asList("a","b"); String[] arr1 = list.stream().toArray(size -> { System.out.println(size); return new String[size]; }); String s = StringUtils.join(list, " "); System.out.println(s);*/ /*double v = 1.4999; String s = new BigDecimal(v).setScale(2, BigDecimal.ROUND_HALF_UP).toString(); System.out.println(s);*/ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm"); Date date1 = sdf.parse("2018-06-06 12:00:00"); Date date2 = sdf.parse("2019-06-06 12:00:00"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); int start = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTime(date2); int end = calendar.get(Calendar.DAY_OF_YEAR); long time = date2.getTime() - date1.getTime(); if(start != end || time > 24 * 60 * 3600 * 1000) { System.out.println("error"); } } @Override public boolean equals(Object obj) { if(obj instanceof Test) { Test t = (Test) obj; if(t.s.equalsIgnoreCase(this.s)) { return true; } } return super.equals(obj); } private static void fun() { for(int i = 1; i<101;i++) { for(int j = 2; ; j++) { if(j >= i) { System.out.println(i); break; } if(i % j == 0) break; } } } @org.junit.Test public void candidate() { List<Integer> list = Arrays.asList(1, 2); listAll(list,""); } private void listAll(List<Integer> list, String s) { for(int i = 0; i< list.size();i++) { List<Integer> list1 = new LinkedList<>(list); String temp = s + list.get(i); System.out.println(temp); list1.remove(i); listAll(list1,temp); } } @org.junit.Test public void dserialize() throws IOException, ClassNotFoundException { try (ObjectInputStream is = new ObjectInputStream(new FileInputStream("test.txt"))) { Test test = (Test)is.readObject(); System.out.println(test.serialVersionUID); System.out.println(test.list); } } @org.junit.Test public void serialize() throws IOException { Test test = new Test(); System.out.println(test.serialVersionUID); test.list.addAll(Arrays.asList("a","b")); System.out.println(test.list); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("test.txt")); os.writeObject(test); os.close(); } private static void bigDecimal() { BigDecimal bigDecimal = new BigDecimal(1); BigDecimal bigDecimal1 = bigDecimal.setScale(1, BigDecimal.ROUND_DOWN); System.out.println(bigDecimal); System.out.println(bigDecimal1); } /*private static void testLatch() throws InterruptedException { CountDownLatch latch = new CountDownLatch(2); executor.execute(()->{ try { System.out.println("睡眠中"); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } for (int i=0;i<2;i++) { System.out.println("释放:" + i); latch.countDown(); } }); latch.await(); System.out.println("end"); executor.shutdown(); }*/ }
vincentjava/netty-study
src/main/java/com/study/aio/client/Test.java
Java
apache-2.0
5,568
package com.study.aio.client; /** * Created by wusz on 2018/5/17. */ public class TimeClient { public static void main(String[] args) { new Thread(new AsyncTimeClientHandler("127.0.0.1", 8080)).start(); } }
vincentjava/netty-study
src/main/java/com/study/aio/client/TimeClient.java
Java
apache-2.0
226
package com.study.aio.server; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; /** * Created by wusz on 2018/5/16. */ public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel,AsyncTimeServerHandler> { @Override public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) { attachment.asynchronousServerSocketChannel.accept(attachment,this); ByteBuffer buffer = ByteBuffer.allocate(1024); result.read(buffer,buffer,new ReadCompletionHandler(result)); } @Override public void failed(Throwable exc, AsyncTimeServerHandler attachment) { exc.printStackTrace(); attachment.latch.countDown(); } }
vincentjava/netty-study
src/main/java/com/study/aio/server/AcceptCompletionHandler.java
Java
apache-2.0
802
package com.study.aio.server; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.AsynchronousServerSocketChannel; import java.util.concurrent.CountDownLatch; public class AsyncTimeServerHandler implements Runnable { private int port; AsynchronousServerSocketChannel asynchronousServerSocketChannel; CountDownLatch latch; public AsyncTimeServerHandler(int port) { this.port = port; try { asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open(); asynchronousServerSocketChannel.bind(new InetSocketAddress(port)); System.out.println("The time server is start in port:"+port); } catch (IOException e) { e.printStackTrace(); } } public void run() { latch = new CountDownLatch(1); doAccept(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void doAccept() { asynchronousServerSocketChannel.accept(this,new AcceptCompletionHandler()); } }
vincentjava/netty-study
src/main/java/com/study/aio/server/AsyncTimeServerHandler.java
Java
apache-2.0
1,121
package com.study.aio.server; import io.netty.util.internal.StringUtil; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.Date; /** * Created by wusz on 2018/5/16. */ public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> { private AsynchronousSocketChannel channel; public ReadCompletionHandler(AsynchronousSocketChannel channel) { this.channel = channel; } @Override public void completed(Integer result, ByteBuffer attachment) { attachment.flip(); byte[] body = new byte[attachment.remaining()]; attachment.get(body); try { String req = new String(body, "UTF-8"); System.out.println("The time server receive order:"+req); String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(req) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; doWirte(currentTime); } catch (Exception e) { } } private void doWirte(String currentTime) { if(currentTime != null && currentTime.trim().length() > 0) { byte[] bytes = currentTime.getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length); writeBuffer.put(bytes); writeBuffer.flip(); channel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result, ByteBuffer buffer) { if(buffer.hasRemaining()) { channel.write(buffer,buffer,this); } } @Override public void failed(Throwable exc, ByteBuffer buffer) { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } } }); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { try { this.channel.close(); } catch (IOException e) { e.printStackTrace(); } } }
vincentjava/netty-study
src/main/java/com/study/aio/server/ReadCompletionHandler.java
Java
apache-2.0
2,281
package com.study.aio.server; public class TimeServer { public static void main(String[] args) { AsyncTimeServerHandler timeServer = new AsyncTimeServerHandler(8080); new Thread(timeServer,"AIO-AsyncTimeServerHandler-001").start(); } }
vincentjava/netty-study
src/main/java/com/study/aio/server/TimeServer.java
Java
apache-2.0
261
package com.study.four.client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; /** * Created by wusz on 2018/5/28. */ public class TimeClient { public void connect(int port, String host) { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new LineBasedFrameDecoder(1024)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new TimeClientHandler()); } }); ChannelFuture f = b.connect(host, port).sync(); f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } public static void main(String[] args) { int port = 8080; new TimeClient().connect(port,"127.0.0.1"); } }
vincentjava/netty-study
src/main/java/com/study/four/client/TimeClient.java
Java
apache-2.0
1,696
package com.study.four.client; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.util.logging.Logger; /** * Created by wusz on 2018/5/28. */ public class TimeClientHandler extends ChannelHandlerAdapter { private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName()); private byte[] req; public TimeClientHandler() { req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warning("Unexpected exception from downstream: " + cause.getMessage()); ctx.close(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { for (int i = 0; i < 2; i++) { ByteBuf msg = Unpooled.buffer(req.length); msg.writeBytes(req); ctx.channel().writeAndFlush(msg); System.out.println("send " + i + " msg..........."); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String message = (String) msg; System.out.println("Now is : " + message); } }
vincentjava/netty-study
src/main/java/com/study/four/client/TimeClientHandler.java
Java
apache-2.0
1,341
package com.study.four.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; /** * Created by wusz on 2018/5/28. */ public class TimeServer { public void bind(int port) { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChildChannelHandler()); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } } private class ChildChannelHandler extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new LineBasedFrameDecoder(1024)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new TimeServerHandler()); } } public static void main(String[] args) { int port = 8080; new TimeServer().bind(port); } }
vincentjava/netty-study
src/main/java/com/study/four/server/TimeServer.java
Java
apache-2.0
1,778
package com.study.four.server; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.util.Date; /** * Created by wusz on 2018/5/28. */ public class TimeServerHandler extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String body = (String) msg; System.out.println("The time server receiver order: " + body); String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; currentTime += System.getProperty("line.separator"); ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes()); ctx.writeAndFlush(resp); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { // ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
vincentjava/netty-study
src/main/java/com/study/four/server/TimeServerHandler.java
Java
apache-2.0
1,098
package com.study.http.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpRequestDecoder; /** * @description: * @author: wusz * @date: 2018/6/8 */ public class HttpFileServer { private static final String DEFAULT_URL = "D:/study"; public void run(final int port, final String url) { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup,workGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-decoder",new HttpRequestDecoder()); } }); } }
vincentjava/netty-study
src/main/java/com/study/http/server/HttpFileServer.java
Java
apache-2.0
1,159
package com.study.nio.client; /** * Create by wusz on 2018/5/14 */ public class TimeClient { public static void main(String[] args) { int port = 8080; new Thread(new TimeClientHandler("127.0.0.1",port)).start(); } }
vincentjava/netty-study
src/main/java/com/study/nio/client/TimeClient.java
Java
apache-2.0
243
package com.study.nio.client; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; /** * Create by wusz on 2018/5/14 */ public class TimeClientHandler implements Runnable { private String host; private int port; private Selector selector; private SocketChannel socketChannel; private boolean stop; public TimeClientHandler(String host, int port) { this.host = host == null ? "127.0.0.1" : host; this.port = port; try { selector = Selector.open(); socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void run() { try { doConnect(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } while (!stop) { try { selector.select(1000); Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectionKeys.iterator(); SelectionKey key = null; while (it.hasNext()) { key = it.next(); it.remove(); try { handleInput(key); } catch (IOException e) { if (key != null) { key.cancel(); if (key.channel() != null) { key.channel().close(); } } } } } catch (IOException e) { e.printStackTrace(); System.exit(1); } } if (selector != null) { try { selector.close(); } catch (IOException e) { e.printStackTrace(); } } } private void handleInput(SelectionKey key) throws IOException { if (key.isValid()) { SocketChannel sc = (SocketChannel) key.channel(); if (key.isConnectable()) { if (sc.finishConnect()) { sc.register(selector, SelectionKey.OP_READ); doWrite(sc); } else { System.exit(1); } } if (key.isReadable()) { ByteBuffer readBuffer = ByteBuffer.allocate(1024); int readBytes = sc.read(readBuffer); if (readBytes > 0) { readBuffer.flip(); byte[] bytes = new byte[readBuffer.remaining()]; readBuffer.get(bytes); String body = new String(bytes, "UTF-8"); System.out.println("Now is : " + body); this.stop = true; } else if (readBytes < 0) { key.cancel(); sc.close(); } else ; } } } private void doConnect() throws IOException { if (socketChannel.connect(new InetSocketAddress(host, port))) { socketChannel.register(selector, SelectionKey.OP_READ); doWrite(socketChannel); } else { socketChannel.register(selector, SelectionKey.OP_CONNECT); } } private void doWrite(SocketChannel sc) throws IOException { byte[] req = "QUERY TIME ORDER".getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(req.length); writeBuffer.put(req); writeBuffer.flip(); sc.write(writeBuffer); if (!writeBuffer.hasRemaining()) { System.out.println("Send order 2 server succeed"); } } }
vincentjava/netty-study
src/main/java/com/study/nio/client/TimeClientHandler.java
Java
apache-2.0
4,048
package com.study.nio.server; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Date; import java.util.Iterator; import java.util.Set; /** * Create by wusz on 2018/5/11 */ public class MultiplexerTimeServer implements Runnable { private int port; private Selector selector; private ServerSocketChannel servChannel; private volatile boolean stop; public MultiplexerTimeServer(int port) { this.port = port; try { selector = Selector.open(); servChannel = ServerSocketChannel.open(); servChannel.configureBlocking(false); servChannel.socket().bind(new InetSocketAddress(port)); servChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("The time server is start in port:"+ port); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void stop() { this.stop = true; } public void run() { while (!stop) { try { selector.select(1000); Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectionKeys.iterator(); SelectionKey key = null; while (it.hasNext()) { key = it.next(); it.remove(); try{ handleInput(key); }catch (Exception e) { if(key != null) { key.cancel(); if(key.channel() != null) { key.channel().close(); } } } } } catch (IOException e) { e.printStackTrace(); } } } private void handleInput(SelectionKey key) throws IOException { if(key.isValid()) { if(key.isAcceptable()) { ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); sc.register(selector,SelectionKey.OP_READ); } if(key.isReadable()) { SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer readBuffer = ByteBuffer.allocate(1024); int readBytes = sc.read(readBuffer); if(readBytes > 0) { readBuffer.flip(); byte[] bytes = new byte[readBuffer.remaining()]; readBuffer.get(bytes); String body = new String(bytes,"UTF-8"); System.out.println("The time server receive order:"+body); String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; doWrite(sc,currentTime); } else if(readBytes < 0) { key.cancel(); sc.close(); } else { } } } } private void doWrite(SocketChannel channel, String response) throws IOException { if(response != null && response.trim().length()>0) { byte[] bytes = response.getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length); writeBuffer.put(bytes); writeBuffer.flip(); channel.write(writeBuffer); } } }
vincentjava/netty-study
src/main/java/com/study/nio/server/MultiplexerTimeServer.java
Java
apache-2.0
3,801
package com.study.nio.server; /** * Create by wusz on 2018/5/11 */ public class TimeServer { public static void main(String[] args) { int port = 8080; MultiplexerTimeServer timeServer = new MultiplexerTimeServer(port); new Thread(timeServer,"NIO-MultiplexerTimeServer").start(); } }
vincentjava/netty-study
src/main/java/com/study/nio/server/TimeServer.java
Java
apache-2.0
318
package com.study.three.client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; /** * Created by wusz on 2018/5/28. */ public class TimeClient { public void connect(int port, String host) { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new LineBasedFrameDecoder(1024)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new TimeClientHandler()); } }); ChannelFuture f = b.connect(host, port).sync(); f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } public static void main(String[] args) { int port = 8080; new TimeClient().connect(port,"127.0.0.1"); } }
vincentjava/netty-study
src/main/java/com/study/three/client/TimeClient.java
Java
apache-2.0
1,697
package com.study.three.client; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.util.logging.Logger; /** * Created by wusz on 2018/5/28. */ public class TimeClientHandler extends ChannelHandlerAdapter { private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName()); private final ByteBuf firstMessage; public TimeClientHandler() { byte[] req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes(); firstMessage = Unpooled.buffer(req.length); firstMessage.writeBytes(req); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warning("Unexpected exception from downstream: " + cause.getMessage()); ctx.close(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { for (int i = 0; i < 10; i++) { ctx.channel().writeAndFlush(firstMessage); System.out.println("send " + i + " msg..........."); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req, "UTF-8"); System.out.println("Now is : " + body); } }
vincentjava/netty-study
src/main/java/com/study/three/client/TimeClientHandler.java
Java
apache-2.0
1,500
package com.study.three.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; /** * Created by wusz on 2018/5/28. */ public class TimeServer { public void bind(int port) { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChildChannelHandler()); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } } private class ChildChannelHandler extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new LineBasedFrameDecoder(1024)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new TimeServerHandler()); } } public static void main(String[] args) { int port = 8080; new TimeServer().bind(port); } }
vincentjava/netty-study
src/main/java/com/study/three/server/TimeServer.java
Java
apache-2.0
1,779
package com.study.three.server; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.util.Date; /** * Created by wusz on 2018/5/28. */ public class TimeServerHandler extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req, "UTF-8"); System.out.println("The time server receiver order: " + body); String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; ByteBuf resp = Unpooled.copiedBuffer((currentTime + System.getProperty("line.separator")).getBytes()); ctx.write(resp); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
vincentjava/netty-study
src/main/java/com/study/three/server/TimeServerHandler.java
Java
apache-2.0
1,198
package com.kariqu.cldld.wss; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; public class CloseFramer extends CloseWebSocketFrame { private CloseFramer(WebsocketStatusCode code) { super(code.getStatusCode(), code.getStr()); } public static CloseFramer normalClose() { return new CloseFramer(WebsocketStatusCode.NORMAL_CLOSE); } public static CloseFramer repeatedLoginClose() { return new CloseFramer(WebsocketStatusCode.REPEATED_LOGIN_CLOSE); } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/CloseFramer.java
Java
unknown
532
package com.kariqu.cldld.wss; public class Main { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new WebSocketServer(7910)); thread.start(); thread.join(); } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/Main.java
Java
unknown
242
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.kariqu.cldld.wss; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.timeout.IdleStateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //import com.sun.xml.internal.bind.v2.runtime.reflect.Accessor; /** * Echoes uppercase content of text frames. */ public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> { private static final Logger logger = LoggerFactory.getLogger(WebSocketFrameHandler.class); public WebSocketFrameHandler() { } //通道创建监听 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { logger.info("channelActive channel_id: {}", ctx.channel().id().asShortText()); } //通道销毁监听 @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { logger.info("channelInactive channel_id: {}", ctx.channel().id().asShortText()); } //监听通道事件 @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; switch (e.state()) { case READER_IDLE: //读取超时 handleReaderIdle(ctx); break; case WRITER_IDLE: //写入超时 handleWriterIdle(ctx); break; case ALL_IDLE: //全部超时 handleAllIdle(ctx); break; default: break; } } } /** * 消息读取 */ @Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { decoder(ctx, frame); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { logger.warn("exception: {}", cause.toString()); closeChannle(ctx); } private void decoder(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof TextWebSocketFrame) { String request_encrypt = ((TextWebSocketFrame) frame).text(); if(request_encrypt.isEmpty() || request_encrypt.trim().isEmpty()) return; String request = ""; // 解密 try { //request = Utility.decrypt(request_encrypt); request = request_encrypt; System.out.println("收到消息-----------》" + request); } catch (Exception e) { Channel channel = ctx.channel(); String str = String.format("decode websocket request decrypt error. shutdownChannel channel: %s %s" , e.toString(), channel.id().asShortText()); throw new UnsupportedOperationException(str); } } else { String message = "unsupported frame type: " + frame.getClass().getName(); throw new UnsupportedOperationException(message); } } private void handleReaderIdle(ChannelHandlerContext ctx) { logger.info("reader idle. {}", ctx.channel().id().asShortText()); closeChannle(ctx); } private void handleWriterIdle(ChannelHandlerContext ctx) { logger.info("writer idle. {}", ctx.channel().id().asShortText()); closeChannle(ctx); } private void handleAllIdle(ChannelHandlerContext ctx) { logger.info("all idle. {}", ctx.channel().id().asShortText()); closeChannle(ctx); } private void closeChannle(ChannelHandlerContext ctx) { Channel channel = ctx.channel(); channel.writeAndFlush(CloseFramer.normalClose()); ChannelFuture f2 = ctx.close(); } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/WebSocketFrameHandler.java
Java
unknown
4,739
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.kariqu.cldld.wss; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.handler.codec.http.*; import io.netty.handler.ssl.SslHandler; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static io.netty.handler.codec.http.HttpMethod.GET; import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** * Outputs index page content. */ public class WebSocketIndexPageHandler extends SimpleChannelInboundHandler<FullHttpRequest> { private static final Logger logger = LoggerFactory.getLogger(WebSocketIndexPageHandler.class); private final String websocketPath; public WebSocketIndexPageHandler(String websocketPath) { this.websocketPath = websocketPath; } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { //super.channelRegistered(ctx); super.channelRegistered(ctx); logger.info("====== channel registered: {}", ctx.channel().id().asLongText()); } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { super.channelUnregistered(ctx); logger.info("====== channel unregistered: {}", ctx.channel().id().asLongText()); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { logger.info("===== handlerAdded {}", ctx.channel().id().asLongText()); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { logger.info("===== handlerRemoved {}", ctx.channel().id().asLongText()); } @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } // Allow only GET methods. if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the index page if ("/".equals(req.uri()) || "/index.html".equals(req.uri())) { String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath); ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); HttpUtil.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); } else { // sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); } logger.info("channelRead0 return"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpUtil.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } } private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) { String protocol = "ws"; if (cp.get(SslHandler.class) != null) { // SSL in use so use Secure WebSockets protocol = "wss"; } return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path; } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/WebSocketIndexPageHandler.java
Java
unknown
4,887
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.kariqu.cldld.wss; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WebSocketServer implements Runnable { private final int PORT; //= Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080")); private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class); public WebSocketServer(int PORT) { this.PORT = PORT; } @Override public void run() { //接收线程组 处理连接请求 EventLoopGroup bossGroup = new NioEventLoopGroup(1); //工作线程组 处理信息读取以及发送 EventLoopGroup workerGroup = new NioEventLoopGroup(1); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new WebSocketServerInitializer()); //初始化通道配置 Channel ch = b.bind(PORT).sync().channel(); //开启监听 客户端连接 log.info("server name: world thread: {}", Thread.currentThread().getId()); ch.closeFuture().sync(); } catch (Exception e) { log.error("exception {}", e.toString()); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/WebSocketServer.java
Java
unknown
2,372
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.kariqu.cldld.wss; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.CharsetUtil; /** * Generates the demo HTML page which is served at http://localhost:8080/ */ public final class WebSocketServerIndexPage { private static final String NEWLINE = "\r\n"; public static ByteBuf getContent(String webSocketLocation) { return Unpooled.copiedBuffer( "<html><head><title>Web Socket Test</title></head>" + NEWLINE + "<body>" + NEWLINE + "<script type=\"text/javascript\">" + NEWLINE + "var socket;" + NEWLINE + "if (!window.WebSocket) {" + NEWLINE + " window.WebSocket = window.MozWebSocket;" + NEWLINE + '}' + NEWLINE + "if (window.WebSocket) {" + NEWLINE + " socket = new WebSocket(\"" + webSocketLocation + "\");" + NEWLINE + " socket.onmessage = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = ta.value + '\\n' + event.data" + NEWLINE + " };" + NEWLINE + " socket.onopen = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = \"Web Socket opened!\";" + NEWLINE + " };" + NEWLINE + " socket.onclose = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = ta.value + \"Web Socket closed\"; " + NEWLINE + " };" + NEWLINE + "} else {" + NEWLINE + " alert(\"Your browser does not support Web Socket.\");" + NEWLINE + '}' + NEWLINE + NEWLINE + "function send(message) {" + NEWLINE + " if (!window.WebSocket) { return; }" + NEWLINE + " if (socket.readyState == WebSocket.OPEN) {" + NEWLINE + " socket.send(message);" + NEWLINE + " } else {" + NEWLINE + " alert(\"The socket is not open.\");" + NEWLINE + " }" + NEWLINE + '}' + NEWLINE + "</script>" + NEWLINE + "<form onsubmit=\"return false;\">" + NEWLINE + "<input type=\"text\" name=\"message\" value=\"Hello, World!\"/>" + "<input type=\"button\" value=\"Send Web Socket Data\"" + NEWLINE + " onclick=\"send(this.form.message.value)\" />" + NEWLINE + "<h3>Output</h3>" + NEWLINE + "<textarea id=\"responseText\" style=\"width:500px;height:300px;\"></textarea>" + NEWLINE + "</form>" + NEWLINE + "</body>" + NEWLINE + "</html>" + NEWLINE, CharsetUtil.US_ASCII); } private WebSocketServerIndexPage() { // Unused } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/WebSocketServerIndexPage.java
Java
unknown
3,686
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.kariqu.cldld.wss; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler; import io.netty.handler.timeout.IdleStateHandler; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.io.FileInputStream; import java.io.InputStream; import java.security.KeyStore; /** */ public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> { private static final String HTTP_PATH = "/http"; private final SSLContext context = null; public WebSocketServerInitializer(/*SslContext sslCtx,*/) { } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); int readTimeout = 5; int writeTimeout = 0; //设置读取写入超时时间 pipeline.addLast(new IdleStateHandler(readTimeout, writeTimeout,0)); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new WebSocketServerCompressionHandler()); pipeline.addLast(new WebSocketServerProtocolHandler("/websocket", null, true)); //设置消息处理器 pipeline.addLast(new WebSocketFrameHandler()); } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/WebSocketServerInitializer.java
Java
unknown
2,233
package com.kariqu.cldld.wss; /* 0-999 Status codes in the range 0-999 are not used. 1000-2999 Status codes in the range 1000-2999 are reserved for definition by this protocol, its future revisions, and extensions specified in a permanent and readily available public specification. 3000-3999 Status codes in the range 3000-3999 are reserved for use by libraries, frameworks, and applications. These status codes are registered directly with IANA. The interpretation of these codes is undefined by this protocol. 4000-4999 Status codes in the range 4000-4999 are reserved for private use and thus can't be registered. Such codes can be used by prior agreements between WebSocket applications. The interpretation of these codes is undefined by this protocol. */ public enum WebsocketStatusCode { NORMAL_CLOSE(4000, "normal_close"), // 正常关闭 REPEATED_LOGIN_CLOSE(4001, "repeated_login_close"); // 重复登陆关闭 private int statusCode; private String str; private WebsocketStatusCode(int code, String str) { this.statusCode = code; this.str = str; } public int getStatusCode() { return statusCode; } public String getStr() { return str; } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/WebsocketStatusCode.java
Java
unknown
1,419
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * <p>This package contains an example web socket web server. * <p>The web server only handles text, ping and closing frames. For text frames, * it echoes the received text in upper case. * <p>Once started, you can test the web server against your browser by navigating * to http://localhost:8080/ * <p>You can also test it with a web socket client. Send web socket traffic to * ws://localhost:8080/websocket. */ package com.kariqu.cldld.wss;
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/package-info.java
Java
unknown
1,091
cmake_minimum_required(VERSION 3.1 FATAL_ERROR) file(STRINGS "${CMAKE_CURRENT_LIST_DIR}/src/oatpp/core/base/Environment.hpp" OATPP_VERSION_MACRO REGEX "#define OATPP_VERSION \"[0-9]+.[0-9]+.[0-9]+\"$") string(REGEX REPLACE "#define OATPP_VERSION \"([0-9]+.[0-9]+.[0-9]+)\"$" "\\1" oatpp_VERSION "${OATPP_VERSION_MACRO}") ################################################################################################### ## These variables are passed to oatpp-module-install.cmake script ## use these variables to configure module installation set(OATPP_THIS_MODULE_NAME oatpp) ## name of the module (also name of folders in installation dirs) set(OATPP_THIS_MODULE_VERSION ${oatpp_VERSION}) ## version of the module (also sufix of folders in installation dirs) ################################################################################################### project(oatpp VERSION ${OATPP_THIS_MODULE_VERSION} LANGUAGES CXX) option(BUILD_SHARED_LIBS "Build shared libraries" OFF) option(OATPP_INSTALL "Create installation target for oat++" ON) option(OATPP_BUILD_TESTS "Create test target for oat++" ON) option(OATPP_LINK_TEST_LIBRARY "Link oat++ test library" ON) option(OATPP_LINK_ATOMIC "Link atomic library for other platform than MSVC|MINGW|APPLE|FreeBSD" ON) option(OATPP_MSVC_LINK_STATIC_RUNTIME "MSVC: Link with static runtime (/MT and /MTd)." OFF) ################################################################################################### ## COMPILATION CONFIG ############################################################################# ################################################################################################### if(OATPP_LINK_TEST_LIBRARY) set(OATPP_THIS_MODULE_LIBRARIES oatpp oatpp-test) ## list of libraries to find when find_package is called set(OATPP_THIS_MODULE_TARGETS oatpp oatpp-test) ## list of targets to install set(OATPP_THIS_MODULE_DIRECTORIES oatpp oatpp-test) ## list of directories to install else() set(OATPP_THIS_MODULE_LIBRARIES oatpp) ## list of libraries to find when find_package is called set(OATPP_THIS_MODULE_TARGETS oatpp) ## list of targets to install set(OATPP_THIS_MODULE_DIRECTORIES oatpp) ## list of directories to install endif() option(OATPP_DISABLE_ENV_OBJECT_COUNTERS "Disable object counting for Release builds for better performance" OFF) option(OATPP_DISABLE_POOL_ALLOCATIONS "This will make oatpp::base::memory::MemoryPool, method obtain and free call new and delete directly" OFF) set(OATPP_THREAD_HARDWARE_CONCURRENCY "AUTO" CACHE STRING "Predefined value for function oatpp::concurrency::Thread::getHardwareConcurrency()") option(OATPP_COMPAT_BUILD_NO_THREAD_LOCAL "Disable 'thread_local' feature" OFF) option(OATPP_COMPAT_BUILD_NO_SET_AFFINITY "No 'pthread_setaffinity_np' method" OFF) option(OATPP_DISABLE_LOGV "DISABLE logs priority V" OFF) option(OATPP_DISABLE_LOGD "DISABLE logs priority D" OFF) option(OATPP_DISABLE_LOGI "DISABLE logs priority I" OFF) option(OATPP_DISABLE_LOGW "DISABLE logs priority W" OFF) option(OATPP_DISABLE_LOGE "DISABLE logs priority E" OFF) ## Print config ################################################################################## message("\n############################################################################") message("## oatpp module compilation config:\n") message("OATPP_DISABLE_ENV_OBJECT_COUNTERS=${OATPP_DISABLE_ENV_OBJECT_COUNTERS}") message("OATPP_THREAD_HARDWARE_CONCURRENCY=${OATPP_THREAD_HARDWARE_CONCURRENCY}") message("OATPP_COMPAT_BUILD_NO_THREAD_LOCAL=${OATPP_COMPAT_BUILD_NO_THREAD_LOCAL}") ## Set definitions ############################################################################### if(OATPP_DISABLE_ENV_OBJECT_COUNTERS) add_definitions(-DOATPP_DISABLE_ENV_OBJECT_COUNTERS) endif() if(OATPP_DISABLE_POOL_ALLOCATIONS) add_definitions (-DOATPP_DISABLE_POOL_ALLOCATIONS) message("WARNING: OATPP_DISABLE_POOL_ALLOCATIONS option is deprecated and has no effect.") endif() set(AUTO_VALUE AUTO) if(NOT OATPP_THREAD_HARDWARE_CONCURRENCY STREQUAL AUTO_VALUE) add_definitions (-DOATPP_THREAD_HARDWARE_CONCURRENCY=${OATPP_THREAD_HARDWARE_CONCURRENCY}) endif() if(OATPP_THREAD_DISTRIBUTED_MEM_POOL_SHARDS_COUNT) add_definitions (-DOATPP_THREAD_DISTRIBUTED_MEM_POOL_SHARDS_COUNT=${OATPP_THREAD_DISTRIBUTED_MEM_POOL_SHARDS_COUNT}) message("WARNING: OATPP_THREAD_DISTRIBUTED_MEM_POOL_SHARDS_COUNT option is deprecated and has no effect.") endif() if(OATPP_COMPAT_BUILD_NO_THREAD_LOCAL) add_definitions(-DOATPP_COMPAT_BUILD_NO_THREAD_LOCAL) endif() if(OATPP_COMPAT_BUILD_NO_SET_AFFINITY) add_definitions(-DOATPP_COMPAT_BUILD_NO_SET_AFFINITY) endif() if(OATPP_DISABLE_LOGV) add_definitions(-DOATPP_DISABLE_LOGV) endif() if(OATPP_DISABLE_LOGD) add_definitions(-DOATPP_DISABLE_LOGD) endif() if(OATPP_DISABLE_LOGI) add_definitions(-DOATPP_DISABLE_LOGI) endif() if(OATPP_DISABLE_LOGW) add_definitions(-DOATPP_DISABLE_LOGW) endif() if(OATPP_DISABLE_LOGE) add_definitions(-DOATPP_DISABLE_LOGE) endif() if(CMAKE_COMPILER_IS_GNUCXX AND ${CMAKE_CXX_COMPILER_VERSION} VERSION_LESS 5.0) add_definitions(-DOATPP_DISABLE_STD_PUT_TIME) endif() message("\n############################################################################\n") ################################################################################################### message("oatpp version: '${OATPP_THIS_MODULE_VERSION}'") #SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address") #SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=thread") include(cmake/msvc-runtime.cmake) configure_msvc_runtime() add_subdirectory(src) if(OATPP_BUILD_TESTS) enable_testing() add_subdirectory(test) endif() include(cpack.cmake) # This must always be last! include( CPack )
vincent-in-black-sesame/oat
CMakeLists.txt
CMake
apache-2.0
5,776
@PACKAGE_INIT@ if(NOT TARGET oatpp::@OATPP_MODULE_NAME@) include("${CMAKE_CURRENT_LIST_DIR}/@OATPP_MODULE_NAME@Targets.cmake") endif() set_and_check(@OATPP_MODULE_NAME@_INCLUDE_DIRS "${PACKAGE_PREFIX_DIR}/include/oatpp-@OATPP_MODULE_VERSION@/@OATPP_MODULE_NAME@/") set_and_check(@OATPP_MODULE_NAME@_LIBRARIES_DIRS "${PACKAGE_PREFIX_DIR}/@OATPP_MODULE_LIBDIR@/oatpp-@OATPP_MODULE_VERSION@/") set(@OATPP_MODULE_NAME@_LIBRARIES @OATPP_MODULE_LIBRARIES@) set(OATPP_BASE_DIR "${PACKAGE_PREFIX_DIR}/include/oatpp-@OATPP_MODULE_VERSION@/")
vincent-in-black-sesame/oat
cmake/module-config.cmake.in
CMake
apache-2.0
540
####################################################################################### ## Set module properties ## all oatpp modules should have the same installation procedure ## ## installation tree: ## ## prefix/ ## | ## |- include/oatpp-<version>/<module-name> ## - lib/ ## | ## |- cmake/<module-name>-<version>/ ## | | ## | |- <module-name>Config.cmake ## | - <module-name>ConfigVersion.cmake ## | ## - oatpp-<version>/ ## | ## |- lib1.a ## |- lib2.a ## - ... ## ###################################################################################### message("\n############################################################################") message("## oatpp-module-install.cmake\n") message("OATPP_THIS_MODULE_NAME=${OATPP_THIS_MODULE_NAME}") message("OATPP_THIS_MODULE_VERSION=${OATPP_THIS_MODULE_VERSION}") message("OATPP_THIS_MODULE_LIBRARIES=${OATPP_THIS_MODULE_LIBRARIES}") message("OATPP_THIS_MODULE_TARGETS=${OATPP_THIS_MODULE_TARGETS}") message("OATPP_THIS_MODULE_DIRECTORIES=${OATPP_THIS_MODULE_DIRECTORIES}") message("\n############################################################################\n") ####################################################################################### ## Set cache variables to configure module-config.cmake.in template ## via call to configure_package_config_file include(GNUInstallDirs) set(OATPP_MODULE_NAME ${OATPP_THIS_MODULE_NAME} CACHE STRING "oatpp module name") set(OATPP_MODULE_VERSION "${OATPP_THIS_MODULE_VERSION}" CACHE STRING "oatpp module version") set(OATPP_MODULE_LIBRARIES "${OATPP_THIS_MODULE_LIBRARIES}" ## list libraries to find when find_package is called CACHE INTERNAL "oatpp module libraries" ) set(OATPP_MODULE_LIBDIR ${CMAKE_INSTALL_LIBDIR} CACHE STRING "lib folder name") ####################################################################################### ## calc directories to install (relative to this script) ## dirs should be in ( relative ../src/<dirs>) foreach(CURR_DIR ${OATPP_THIS_MODULE_DIRECTORIES}) list(APPEND OATPP_DIRS_TO_INSTALL ${CMAKE_CURRENT_LIST_DIR}/../src/${CURR_DIR}) endforeach() ####################################################################################### install( TARGETS ${OATPP_THIS_MODULE_TARGETS} EXPORT "${OATPP_MODULE_NAME}Targets" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}/oatpp-${OATPP_MODULE_VERSION}" COMPONENT Devel LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}/oatpp-${OATPP_MODULE_VERSION}" COMPONENT Library RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}/oatpp-${OATPP_MODULE_VERSION}" COMPONENT Library INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/oatpp-${OATPP_MODULE_VERSION}/${OATPP_MODULE_NAME}" ) install(DIRECTORY ${OATPP_DIRS_TO_INSTALL} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/oatpp-${OATPP_MODULE_VERSION}/${OATPP_MODULE_NAME}" COMPONENT Devel FILES_MATCHING PATTERN "*.hpp" ) install(EXPORT "${OATPP_MODULE_NAME}Targets" FILE "${OATPP_MODULE_NAME}Targets.cmake" NAMESPACE oatpp:: DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${OATPP_MODULE_NAME}-${OATPP_MODULE_VERSION}" COMPONENT Devel ) include(CMakePackageConfigHelpers) write_basic_package_version_file("${OATPP_MODULE_NAME}ConfigVersion.cmake" VERSION ${OATPP_MODULE_VERSION} COMPATIBILITY ExactVersion ## Use exact version matching. ) ## Take module-config.cmake.in file in this direcory as a template configure_package_config_file( "${CMAKE_CURRENT_LIST_DIR}/module-config.cmake.in" "${OATPP_MODULE_NAME}Config.cmake" INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${OATPP_MODULE_NAME}-${OATPP_MODULE_VERSION}" PATH_VARS OATPP_MODULE_NAME OATPP_MODULE_VERSION OATPP_MODULE_LIBRARIES OATPP_MODULE_LIBDIR NO_CHECK_REQUIRED_COMPONENTS_MACRO ) install( FILES "${CMAKE_CURRENT_BINARY_DIR}/${OATPP_MODULE_NAME}Config.cmake" "${CMAKE_CURRENT_BINARY_DIR}/${OATPP_MODULE_NAME}ConfigVersion.cmake" DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${OATPP_MODULE_NAME}-${OATPP_MODULE_VERSION}" COMPONENT Devel )
vincent-in-black-sesame/oat
cmake/module-install.cmake
CMake
apache-2.0
4,366
macro(configure_msvc_runtime) if(MSVC) # Set compiler options. set(variables CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_RELWITHDEBINFO CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELWITHDEBINFO) if(OATPP_MSVC_LINK_STATIC_RUNTIME) message(STATUS "MSVC: using statically-linked runtime (/MT and /MTd).") foreach(variable ${variables}) if(${variable} MATCHES "/MD") string(REGEX REPLACE "/MD" "/MT" ${variable} "${${variable}}") endif() endforeach() else() message(STATUS "MSVC: using dynamically-linked runtime (/MD and /MDd).") foreach(variable ${variables}) if(${variable} MATCHES "/MT") string(REGEX REPLACE "/MT" "/MD" ${variable} "${${variable}}") endif() endforeach() endif() foreach(variable ${variables}) set(${variable} "${${variable}}" CACHE STRING "MSVC_${variable}" FORCE) endforeach() endif() endmacro(configure_msvc_runtime)
vincent-in-black-sesame/oat
cmake/msvc-runtime.cmake
CMake
apache-2.0
1,079
# # Packaging # https://cmake.org/cmake/help/latest/module/CPack.html # set( CPACK_PACKAGE_NAME ${PROJECT_NAME} ) set( CPACK_PACKAGE_VENDOR "Balluff" ) set( CPACK_PACKAGE_DESCRIPTION_SUMMARY "oatpp - Light and powerful C++ web framework" ) set( CPACK_PACKAGE_HOMEPAGE_URL "https://github.com/oatpp/oatpp" ) set( CPACK_PACKAGE_CONTACT "https://github.com/oatpp/oatpp" ) set( CPACK_PACKAGE_VERSION ${OATPP_THIS_MODULE_VERSION} ) set( CPACK_PACKAGE_INSTALL_DIRECTORY ${PROJECT_NAME} ) get_filename_component( oatpp_root_dir ${CMAKE_CURRENT_SOURCE_DIR} DIRECTORY ) set( CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE" ) set( CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md" ) set( CPACK_COMPONENT_Library_DISPLAY_NAME "oatpp Library" ) set( CPACK_COMPONENT_Library_DESCRIPTION "The oatpp binary library." ) set( CPACK_COMPONENT_Library_REQUIRED 1 ) set( CPACK_COMPONENT_Devel_DISPLAY_NAME "oatpp Development Files" ) set( CPACK_COMPONENT_Devel_DESCRIPTION "Development files for compiling against oatpp." ) set( CPACK_COMPONENT_Devel_REQUIRED 0 ) if( ${CMAKE_SYSTEM_NAME} STREQUAL "Linux" ) if ( "${CPACK_PACKAGE_ARCHITECTURE}" STREQUAL "" ) # Note: the architecture should default to the local architecture, but it # in fact comes up empty. We call `uname -m` to ask the kernel instead. EXECUTE_PROCESS( COMMAND uname -m COMMAND tr -d '\n' OUTPUT_VARIABLE CPACK_PACKAGE_ARCHITECTURE ) endif() set( CPACK_INCLUDE_TOPLEVEL_DIRECTORY 1 ) set( CPACK_PACKAGE_RELEASE 1 ) # RPM - https://cmake.org/cmake/help/latest/cpack_gen/rpm.html set( CPACK_RPM_PACKAGE_RELEASE ${CPACK_PACKAGE_RELEASE} ) set( CPACK_RPM_PACKAGE_ARCHITECTURE ${CPACK_PACKAGE_ARCHITECTURE} ) set( CPACK_RPM_PACKAGE_DESCRIPTION ${CPACK_PACKAGE_DESCRIPTION_SUMMARY} ) set( CPACK_RPM_PACKAGE_URL ${CPACK_PACKAGE_HOMEPAGE_URL} ) set( CPACK_RPM_PACKAGE_LICENSE "APACHE-2" ) set( CPACK_RPM_COMPONENT_INSTALL 1 ) set( CPACK_RPM_MAIN_COMPONENT "Library" ) set( CPACK_RPM_COMPRESSION_TYPE "xz" ) set( CPACK_RPM_PACKAGE_AUTOPROV 1 ) set( CPACK_RPM_PACKAGE_NAME "${CPACK_PACKAGE_NAME}" ) set( CPACK_RPM_FILE_NAME "RPM-DEFAULT" ) set( CPACK_RPM_Library_PACKAGE_ARCHITECTURE ${CPACK_PACKAGE_ARCHITECTURE} ) set( CPACK_RPM_Library_PACKAGE_NAME ${CPACK_PACKAGE_NAME} ) set( CPACK_RPM_Library_FILE_NAME "${CPACK_RPM_Library_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CPACK_RPM_PACKAGE_RELEASE}.${CPACK_RPM_Library_PACKAGE_ARCHITECTURE}.rpm" ) set( CPACK_RPM_Library_PACKAGE_SUMMARY ${CPACK_COMPONENT_Library_DESCRIPTION} ) set( CPACK_RPM_Devel_PACKAGE_REQUIRES "cmake >= ${CMAKE_MINIMUM_REQUIRED_VERSION},oatpp >= ${CPACK_PACKAGE_VERSION}" ) set( CPACK_RPM_Devel_PACKAGE_SUMMARY ${CPACK_COMPONENT_Devel_DESCRIPTION} ) set( CPACK_RPM_Devel_PACKAGE_ARCHITECTURE "noarch" ) # only contains headers and cmake files set( CPACK_RPM_Devel_PACKAGE_NAME "${CPACK_PACKAGE_NAME}-devel" ) set( CPACK_RPM_Devel_FILE_NAME "${CPACK_RPM_Devel_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CPACK_RPM_PACKAGE_RELEASE}.${CPACK_RPM_Devel_PACKAGE_ARCHITECTURE}.rpm" ) # DEB - https://cmake.org/cmake/help/latest/cpack_gen/deb.html set( CPACK_DEBIAN_PACKAGE_NAME "${CPACK_PACKAGE_NAME}-dev" ) set( CPACK_DEBIAN_PACKAGE_RELEASE ${CPACK_PACKAGE_RELEASE} ) set( CPACK_DEBIAN_PACKAGE_HOMEPAGE ${CPACK_PACKAGE_HOMEPAGE_URL} ) set( CPACK_DEB_COMPONENT_INSTALL 1 ) set( CPACK_DEBIAN_COMPRESSION_TYPE "xz") if ( ${CPACK_PACKAGE_ARCHITECTURE} STREQUAL "x86_64" ) set( CPACK_DEBIAN_PACKAGE_ARCHITECTURE "amd64" ) # DEB doesn't always use the kernel's arch name else() set( CPACK_DEBIAN_PACKAGE_ARCHITECTURE ${CPACK_PACKAGE_ARCHITECTURE} ) endif() set( CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT" ) # Use default naming scheme set( CPACK_DEBIAN_LIBRARY_PACKAGE_NAME ${CPACK_PACKAGE_NAME} ) set( CPACK_DEBIAN_LIBRARY_PACKAGE_SHLIBDEPS 1 ) set( CPACK_DEBIAN_DEVEL_PACKAGE_DEPENDS "cmake (>= ${CMAKE_MINIMUM_REQUIRED_VERSION}), oatpp (>= ${CPACK_PACKAGE_VERSION})" ) set( CPACK_DEBIAN_DEVEL_PACKAGE_NAME "${CPACK_PACKAGE_NAME}-dev" ) elseif( ${CMAKE_HOST_WIN32} ) set( CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL ON ) set( CPACK_NSIS_DISPLAY_NAME ${PROJECT_NAME} ) set( CPACK_NSIS_PACKAGE_NAME ${PROJECT_NAME} ) set( CPACK_NSIS_URL_INFO_ABOUT ${CPACK_PACKAGE_HOMEPAGE_URL} ) endif()
vincent-in-black-sesame/oat
cpack.cmake
CMake
apache-2.0
4,474
#include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/macro/codegen.hpp" typedef oatpp::parser::Caret ParsingCaret; typedef oatpp::parser::json::mapping::Serializer Serializer; typedef oatpp::parser::json::mapping::Deserializer Deserializer; #include OATPP_CODEGEN_BEGIN(DTO) class EmptyDto : public oatpp::DTO { DTO_INIT(EmptyDto, DTO) }; class Test1 : public oatpp::DTO { DTO_INIT(Test1, DTO) DTO_FIELD(String, strF); }; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { oatpp::String input(reinterpret_cast<const char*>(data), size); oatpp::parser::json::mapping::ObjectMapper mapper; try { mapper.readFromString<oatpp::Object<Test1>>(input); } catch(...) {} return 0; }
vincent-in-black-sesame/oat
fuzzers/oatpp/parser/json/mapping/ObjectMapper.cpp
C++
apache-2.0
745
####################################################################################################### ## oatpp add_library(oatpp oatpp/algorithm/CRC.cpp oatpp/algorithm/CRC.hpp oatpp/codegen/ApiClient_define.hpp oatpp/codegen/ApiClient_undef.hpp oatpp/codegen/api_controller/base_define.hpp oatpp/codegen/api_controller/base_undef.hpp oatpp/codegen/api_controller/auth_define.hpp oatpp/codegen/api_controller/auth_undef.hpp oatpp/codegen/api_controller/bundle_define.hpp oatpp/codegen/api_controller/bundle_undef.hpp oatpp/codegen/api_controller/cors_define.hpp oatpp/codegen/api_controller/cors_undef.hpp oatpp/codegen/ApiController_define.hpp oatpp/codegen/ApiController_undef.hpp oatpp/codegen/DbClient_define.hpp oatpp/codegen/DbClient_undef.hpp oatpp/codegen/dto/base_define.hpp oatpp/codegen/dto/base_undef.hpp oatpp/codegen/dto/enum_define.hpp oatpp/codegen/dto/enum_undef.hpp oatpp/codegen/DTO_define.hpp oatpp/codegen/DTO_undef.hpp oatpp/core/Types.hpp oatpp/core/async/utils/FastQueue.hpp oatpp/core/async/Coroutine.cpp oatpp/core/async/Coroutine.hpp oatpp/core/async/CoroutineWaitList.cpp oatpp/core/async/CoroutineWaitList.hpp oatpp/core/async/Error.cpp oatpp/core/async/Error.hpp oatpp/core/async/Executor.cpp oatpp/core/async/Executor.hpp oatpp/core/async/Lock.cpp oatpp/core/async/Lock.hpp oatpp/core/async/Processor.cpp oatpp/core/async/Processor.hpp oatpp/core/async/worker/Worker.cpp oatpp/core/async/worker/Worker.hpp oatpp/core/async/worker/IOEventWorker_common.cpp oatpp/core/async/worker/IOEventWorker_kqueue.cpp oatpp/core/async/worker/IOEventWorker_epoll.cpp oatpp/core/async/worker/IOEventWorker_stub.cpp oatpp/core/async/worker/IOEventWorker.hpp oatpp/core/async/worker/IOWorker.cpp oatpp/core/async/worker/IOWorker.hpp oatpp/core/async/worker/TimerWorker.cpp oatpp/core/async/worker/TimerWorker.hpp oatpp/core/base/CommandLineArguments.cpp oatpp/core/base/CommandLineArguments.hpp oatpp/core/base/Config.hpp oatpp/core/base/Countable.cpp oatpp/core/base/Countable.hpp oatpp/core/base/Environment.cpp oatpp/core/base/Environment.hpp oatpp/core/base/ObjectHandle.hpp oatpp/core/concurrency/SpinLock.cpp oatpp/core/concurrency/SpinLock.hpp oatpp/core/concurrency/Thread.cpp oatpp/core/concurrency/Thread.hpp oatpp/core/IODefinitions.cpp oatpp/core/IODefinitions.hpp oatpp/core/data/buffer/FIFOBuffer.cpp oatpp/core/data/buffer/FIFOBuffer.hpp oatpp/core/data/buffer/IOBuffer.cpp oatpp/core/data/buffer/IOBuffer.hpp oatpp/core/data/buffer/Processor.cpp oatpp/core/data/buffer/Processor.hpp oatpp/core/data/mapping/ObjectMapper.cpp oatpp/core/data/mapping/ObjectMapper.hpp oatpp/core/data/mapping/TypeResolver.cpp oatpp/core/data/mapping/TypeResolver.hpp oatpp/core/data/mapping/type/Any.cpp oatpp/core/data/mapping/type/Any.hpp oatpp/core/data/mapping/type/Collection.hpp oatpp/core/data/mapping/type/Enum.cpp oatpp/core/data/mapping/type/Enum.hpp oatpp/core/data/mapping/type/List.cpp oatpp/core/data/mapping/type/List.hpp oatpp/core/data/mapping/type/Map.hpp oatpp/core/data/mapping/type/PairList.cpp oatpp/core/data/mapping/type/PairList.hpp oatpp/core/data/mapping/type/Object.cpp oatpp/core/data/mapping/type/Object.hpp oatpp/core/data/mapping/type/Primitive.cpp oatpp/core/data/mapping/type/Primitive.hpp oatpp/core/data/mapping/type/Type.cpp oatpp/core/data/mapping/type/Type.hpp oatpp/core/data/mapping/type/UnorderedMap.cpp oatpp/core/data/mapping/type/UnorderedMap.hpp oatpp/core/data/mapping/type/UnorderedSet.cpp oatpp/core/data/mapping/type/UnorderedSet.hpp oatpp/core/data/mapping/type/Vector.cpp oatpp/core/data/mapping/type/Vector.hpp oatpp/core/data/resource/File.cpp oatpp/core/data/resource/File.hpp oatpp/core/data/resource/InMemoryData.cpp oatpp/core/data/resource/InMemoryData.hpp oatpp/core/data/resource/Resource.hpp oatpp/core/data/resource/TemporaryFile.cpp oatpp/core/data/resource/TemporaryFile.hpp oatpp/core/data/share/LazyStringMap.hpp oatpp/core/data/share/MemoryLabel.cpp oatpp/core/data/share/MemoryLabel.hpp oatpp/core/data/share/StringTemplate.cpp oatpp/core/data/share/StringTemplate.hpp oatpp/core/data/stream/BufferStream.cpp oatpp/core/data/stream/BufferStream.hpp oatpp/core/data/stream/FIFOStream.cpp oatpp/core/data/stream/FIFOStream.hpp oatpp/core/data/stream/FileStream.cpp oatpp/core/data/stream/FileStream.hpp oatpp/core/data/stream/Stream.cpp oatpp/core/data/stream/Stream.hpp oatpp/core/data/stream/StreamBufferedProxy.cpp oatpp/core/data/stream/StreamBufferedProxy.hpp oatpp/core/data/Bundle.cpp oatpp/core/data/Bundle.hpp oatpp/core/macro/basic.hpp oatpp/core/macro/codegen.hpp oatpp/core/macro/component.hpp oatpp/core/parser/Caret.cpp oatpp/core/parser/Caret.hpp oatpp/core/parser/ParsingError.cpp oatpp/core/parser/ParsingError.hpp oatpp/core/provider/Invalidator.hpp oatpp/core/provider/Pool.hpp oatpp/core/provider/Provider.hpp oatpp/core/utils/Binary.cpp oatpp/core/utils/Binary.hpp oatpp/core/utils/ConversionUtils.cpp oatpp/core/utils/ConversionUtils.hpp oatpp/core/utils/Random.cpp oatpp/core/utils/Random.hpp oatpp/core/utils/String.cpp oatpp/core/utils/String.hpp oatpp/encoding/Base64.cpp oatpp/encoding/Base64.hpp oatpp/encoding/Hex.cpp oatpp/encoding/Hex.hpp oatpp/encoding/Unicode.cpp oatpp/encoding/Unicode.hpp oatpp/network/monitor/ConnectionInactivityChecker.cpp oatpp/network/monitor/ConnectionInactivityChecker.hpp oatpp/network/monitor/ConnectionMaxAgeChecker.cpp oatpp/network/monitor/ConnectionMaxAgeChecker.hpp oatpp/network/monitor/ConnectionMonitor.cpp oatpp/network/monitor/ConnectionMonitor.hpp oatpp/network/monitor/MetricsChecker.hpp oatpp/network/monitor/StatCollector.hpp oatpp/network/tcp/client/ConnectionProvider.cpp oatpp/network/tcp/client/ConnectionProvider.hpp oatpp/network/tcp/server/ConnectionProvider.cpp oatpp/network/tcp/server/ConnectionProvider.hpp oatpp/network/tcp/Connection.cpp oatpp/network/tcp/Connection.hpp oatpp/network/virtual_/Interface.cpp oatpp/network/virtual_/Interface.hpp oatpp/network/virtual_/Pipe.cpp oatpp/network/virtual_/Pipe.hpp oatpp/network/virtual_/Socket.cpp oatpp/network/virtual_/Socket.hpp oatpp/network/virtual_/client/ConnectionProvider.cpp oatpp/network/virtual_/client/ConnectionProvider.hpp oatpp/network/virtual_/server/ConnectionProvider.cpp oatpp/network/virtual_/server/ConnectionProvider.hpp oatpp/network/Address.cpp oatpp/network/Address.hpp oatpp/network/ConnectionHandler.hpp oatpp/network/ConnectionPool.cpp oatpp/network/ConnectionPool.hpp oatpp/network/ConnectionProvider.cpp oatpp/network/ConnectionProvider.hpp oatpp/network/ConnectionProviderSwitch.cpp oatpp/network/ConnectionProviderSwitch.hpp oatpp/network/Server.cpp oatpp/network/Server.hpp oatpp/network/Url.cpp oatpp/network/Url.hpp oatpp/orm/Connection.hpp oatpp/orm/DbClient.cpp oatpp/orm/DbClient.hpp oatpp/orm/Executor.cpp oatpp/orm/Executor.hpp oatpp/orm/QueryResult.cpp oatpp/orm/QueryResult.hpp oatpp/orm/SchemaMigration.cpp oatpp/orm/SchemaMigration.hpp oatpp/orm/Transaction.cpp oatpp/orm/Transaction.hpp oatpp/parser/json/Beautifier.cpp oatpp/parser/json/Beautifier.hpp oatpp/parser/json/Utils.cpp oatpp/parser/json/Utils.hpp oatpp/parser/json/mapping/Deserializer.cpp oatpp/parser/json/mapping/Deserializer.hpp oatpp/parser/json/mapping/ObjectMapper.cpp oatpp/parser/json/mapping/ObjectMapper.hpp oatpp/parser/json/mapping/Serializer.cpp oatpp/parser/json/mapping/Serializer.hpp oatpp/web/client/ApiClient.cpp oatpp/web/client/ApiClient.hpp oatpp/web/client/HttpRequestExecutor.cpp oatpp/web/client/HttpRequestExecutor.hpp oatpp/web/client/RequestExecutor.cpp oatpp/web/client/RequestExecutor.hpp oatpp/web/client/RetryPolicy.cpp oatpp/web/client/RetryPolicy.hpp oatpp/web/mime/multipart/FileProvider.cpp oatpp/web/mime/multipart/FileProvider.hpp oatpp/web/mime/multipart/InMemoryDataProvider.cpp oatpp/web/mime/multipart/InMemoryDataProvider.hpp oatpp/web/mime/multipart/Multipart.cpp oatpp/web/mime/multipart/Multipart.hpp oatpp/web/mime/multipart/Part.cpp oatpp/web/mime/multipart/Part.hpp oatpp/web/mime/multipart/PartList.cpp oatpp/web/mime/multipart/PartList.hpp oatpp/web/mime/multipart/PartReader.cpp oatpp/web/mime/multipart/PartReader.hpp oatpp/web/mime/multipart/Reader.cpp oatpp/web/mime/multipart/Reader.hpp oatpp/web/mime/multipart/StatefulParser.cpp oatpp/web/mime/multipart/StatefulParser.hpp oatpp/web/mime/multipart/TemporaryFileProvider.cpp oatpp/web/mime/multipart/TemporaryFileProvider.hpp oatpp/web/protocol/CommunicationError.cpp oatpp/web/protocol/CommunicationError.hpp oatpp/web/protocol/http/Http.cpp oatpp/web/protocol/http/Http.hpp oatpp/web/protocol/http/incoming/BodyDecoder.cpp oatpp/web/protocol/http/incoming/BodyDecoder.hpp oatpp/web/protocol/http/incoming/Request.cpp oatpp/web/protocol/http/incoming/Request.hpp oatpp/web/protocol/http/incoming/RequestHeadersReader.cpp oatpp/web/protocol/http/incoming/RequestHeadersReader.hpp oatpp/web/protocol/http/incoming/Response.cpp oatpp/web/protocol/http/incoming/Response.hpp oatpp/web/protocol/http/incoming/ResponseHeadersReader.cpp oatpp/web/protocol/http/incoming/ResponseHeadersReader.hpp oatpp/web/protocol/http/incoming/SimpleBodyDecoder.cpp oatpp/web/protocol/http/incoming/SimpleBodyDecoder.hpp oatpp/web/protocol/http/outgoing/Body.cpp oatpp/web/protocol/http/outgoing/Body.hpp oatpp/web/protocol/http/outgoing/BufferBody.cpp oatpp/web/protocol/http/outgoing/BufferBody.hpp oatpp/web/protocol/http/outgoing/MultipartBody.cpp oatpp/web/protocol/http/outgoing/MultipartBody.hpp oatpp/web/protocol/http/outgoing/StreamingBody.cpp oatpp/web/protocol/http/outgoing/StreamingBody.hpp oatpp/web/protocol/http/outgoing/Request.cpp oatpp/web/protocol/http/outgoing/Request.hpp oatpp/web/protocol/http/outgoing/Response.cpp oatpp/web/protocol/http/outgoing/Response.hpp oatpp/web/protocol/http/outgoing/ResponseFactory.cpp oatpp/web/protocol/http/outgoing/ResponseFactory.hpp oatpp/web/protocol/http/encoding/Chunked.cpp oatpp/web/protocol/http/encoding/Chunked.hpp oatpp/web/protocol/http/encoding/ProviderCollection.cpp oatpp/web/protocol/http/encoding/ProviderCollection.hpp oatpp/web/protocol/http/encoding/EncoderProvider.hpp oatpp/web/protocol/http/utils/CommunicationUtils.cpp oatpp/web/protocol/http/utils/CommunicationUtils.hpp oatpp/web/server/AsyncHttpConnectionHandler.cpp oatpp/web/server/AsyncHttpConnectionHandler.hpp oatpp/web/server/HttpConnectionHandler.cpp oatpp/web/server/HttpConnectionHandler.hpp oatpp/web/server/HttpProcessor.cpp oatpp/web/server/HttpProcessor.hpp oatpp/web/server/HttpRequestHandler.hpp oatpp/web/server/HttpRouter.cpp oatpp/web/server/HttpRouter.hpp oatpp/web/server/api/ApiController.cpp oatpp/web/server/api/ApiController.hpp oatpp/web/server/api/Endpoint.cpp oatpp/web/server/api/Endpoint.hpp oatpp/web/server/handler/AuthorizationHandler.cpp oatpp/web/server/handler/AuthorizationHandler.hpp oatpp/web/server/handler/ErrorHandler.cpp oatpp/web/server/handler/ErrorHandler.hpp oatpp/web/server/interceptor/AllowCorsGlobal.cpp oatpp/web/server/interceptor/AllowCorsGlobal.hpp oatpp/web/server/interceptor/RequestInterceptor.hpp oatpp/web/server/interceptor/ResponseInterceptor.hpp oatpp/web/url/mapping/Pattern.cpp oatpp/web/url/mapping/Pattern.hpp oatpp/web/url/mapping/Router.hpp ) set_target_properties(oatpp PROPERTIES CXX_STANDARD 11 CXX_EXTENSIONS OFF CXX_STANDARD_REQUIRED ON ) if (MSVC) target_compile_options(oatpp PRIVATE /permissive-) endif() set(CMAKE_THREAD_PREFER_PTHREAD ON) find_package(Threads REQUIRED) ####################################################################################################### ## Link external libraries SET(OATPP_ADD_LINK_LIBS "") if(MSVC OR MINGW) SET(OATPP_ADD_LINK_LIBS wsock32 ws2_32) elseif(NOT APPLE AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD") if(OATPP_LINK_ATOMIC) SET(OATPP_ADD_LINK_LIBS atomic) endif() endif() message("OATPP_ADD_LINK_LIBS=${OATPP_ADD_LINK_LIBS}") target_link_libraries(oatpp PUBLIC ${CMAKE_THREAD_LIBS_INIT} ${OATPP_ADD_LINK_LIBS} ) target_include_directories(oatpp PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}> ) ####################################################################################################### ## oatpp-test if(OATPP_LINK_TEST_LIBRARY) add_library(oatpp-test oatpp-test/Checker.cpp oatpp-test/Checker.hpp oatpp-test/UnitTest.cpp oatpp-test/UnitTest.hpp oatpp-test/web/ClientServerTestRunner.hpp ) set_target_properties(oatpp-test PROPERTIES CXX_STANDARD 11 CXX_EXTENSIONS OFF CXX_STANDARD_REQUIRED ON ) if (MSVC) target_compile_options(oatpp-test PRIVATE /permissive-) endif() target_link_libraries(oatpp-test PUBLIC oatpp) target_include_directories(oatpp-test PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}> ) add_dependencies(oatpp-test oatpp) endif() ####################################################################################################### ## Install targets if(OATPP_INSTALL) include("../cmake/module-install.cmake") endif()
vincent-in-black-sesame/oat
src/CMakeLists.txt
CMake
apache-2.0
15,263
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Checker.hpp" namespace oatpp { namespace test { PerformanceChecker::PerformanceChecker(const char* tag) : m_tag(tag) , m_ticks(oatpp::base::Environment::getMicroTickCount()) {} PerformanceChecker::~PerformanceChecker(){ v_int64 elapsedTicks = oatpp::base::Environment::getMicroTickCount() - m_ticks; OATPP_LOGD(m_tag, "%d(micro)", elapsedTicks); } v_int64 PerformanceChecker::getElapsedTicks(){ return oatpp::base::Environment::getMicroTickCount() - m_ticks; } ThreadLocalObjectsChecker::ThreadLocalObjectsChecker(const char* tag) : m_tag(tag) , m_objectsCount(oatpp::base::Environment::getThreadLocalObjectsCount()) , m_objectsCreated(oatpp::base::Environment::getThreadLocalObjectsCreated()) { } ThreadLocalObjectsChecker::~ThreadLocalObjectsChecker(){ v_counter leakingObjects = base::Environment::getThreadLocalObjectsCount() - m_objectsCount; v_counter objectsCreatedPerTest = base::Environment::getThreadLocalObjectsCreated() - m_objectsCreated; if(leakingObjects == 0){ OATPP_LOGE(m_tag, "OK:\n created(obj): %d", objectsCreatedPerTest); }else{ OATPP_LOGE(m_tag, "FAILED, leakingObjects = %d", leakingObjects); OATPP_ASSERT(false); } } }}
vincent-in-black-sesame/oat
src/oatpp-test/Checker.cpp
C++
apache-2.0
2,209
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_Checker_hpp #define oatpp_test_Checker_hpp #include "oatpp/core/base/Environment.hpp" namespace oatpp { namespace test { /** * Helper class to check performance of code block. */ class PerformanceChecker { private: const char* m_tag; v_int64 m_ticks; public: /** * Constructor. * @param tag - log tag. */ PerformanceChecker(const char* tag); /** * Non virtual destructor. * Will print time elapsed ticks on destruction. */ ~PerformanceChecker(); /** * Get elapsed time from checker creation. * @return - ticks in microseconds. */ v_int64 getElapsedTicks(); }; /** * Helper class to check block of code on memory leaks. * Checks &id:oatpp::base::Countable; objects, and objects allocated on memory pools. */ class ThreadLocalObjectsChecker { private: class MemoryPoolData { public: const char* name; v_int64 size; v_int64 objectsCount; }; private: const char* m_tag; v_counter m_objectsCount; v_counter m_objectsCreated; public: /** * Constructor. * @param tag - log tag. */ ThreadLocalObjectsChecker(const char* tag); /** * Non virtual destructor. * Will halt program execution if memory leaks detected. */ ~ThreadLocalObjectsChecker(); }; }} #endif /* Checker_hpp */
vincent-in-black-sesame/oat
src/oatpp-test/Checker.hpp
C++
apache-2.0
2,299
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "UnitTest.hpp" #include <chrono> namespace oatpp { namespace test { void UnitTest::run(v_int32 times) { OATPP_LOGI(TAG, "\033[1mSTART\033[0m..."); v_counter objectsCount = base::Environment::getObjectsCount(); v_counter objectsCreated = base::Environment::getObjectsCreated(); before(); v_int64 ticks = base::Environment::getMicroTickCount(); for(v_int32 i = 0; i < times; i++){ onRun(); } v_int64 millis = base::Environment::getMicroTickCount() - ticks; after(); v_counter leakingObjects = base::Environment::getObjectsCount() - objectsCount; v_counter objectsCreatedPerTest = base::Environment::getObjectsCreated() - objectsCreated; if(leakingObjects == 0){ OATPP_LOGI(TAG, "\033[1mFINISHED\033[0m - \033[1;32msuccess!\033[0m"); OATPP_LOGI(TAG, "\033[33m%d(micro), %d(objs)\033[0m\n", millis, objectsCreatedPerTest); }else{ OATPP_LOGE(TAG, "\033[1mFINISHED\033[0m - \033[1;31mfailed\033[0m, leakingObjects = %d", leakingObjects); exit(EXIT_FAILURE); } } }}
vincent-in-black-sesame/oat
src/oatpp-test/UnitTest.cpp
C++
apache-2.0
2,045
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_UnitTest_hpp #define oatpp_test_UnitTest_hpp #include <functional> #include "oatpp/core/base/Environment.hpp" #include "oatpp/core/macro/basic.hpp" namespace oatpp { namespace test { /** * Base class for unit tests. */ class UnitTest{ protected: const char* const TAG; public: /** * Constructor. * @param testTAG - tag used for logs. */ UnitTest(const char* testTAG) : TAG(testTAG) {} /** * Default virtual destructor. */ virtual ~UnitTest() = default; /** * Run this test repeatedly for specified number of times. * @param times - number of times to run this test. */ void run(v_int32 times); /** * Run this test. */ void run(){ run(1); } /** * Override this method. It should contain test logic. */ virtual void onRun() = 0; /** * Optionally override this method. It should contain logic run before all test iterations. */ virtual void before(){}; /** * Optionally override this method. It should contain logic run after all test iterations. */ virtual void after(){}; /** * Run this test repeatedly for specified number of times. * @tparam T - Test class. * @param times - number of times to run this test. */ template<class T> static void runTest(v_int32 times){ T test; test.run(times); } }; #define OATPP_RUN_TEST_0(TEST) \ oatpp::test::UnitTest::runTest<TEST>(1) #define OATPP_RUN_TEST_1(TEST, N) \ oatpp::test::UnitTest::runTest<TEST>(N) /** * Convenience macro to run test. <br> * Usage Example:<br> * `OATPP_RUN_TEST(oatpp::test::web::FullTest);` * Running the test 10 times: * `OATPP_RUN_TEST(oatpp::test::web::FullTest, 10);` */ #define OATPP_RUN_TEST(...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_RUN_TEST_, (__VA_ARGS__)) (__VA_ARGS__)) }} #endif /* oatpp_test_UnitTest_hpp */
vincent-in-black-sesame/oat
src/oatpp-test/UnitTest.hpp
C++
apache-2.0
2,869
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_ClientServerTestRunner_hpp #define oatpp_test_web_ClientServerTestRunner_hpp #include "oatpp/web/server/api/ApiController.hpp" #include "oatpp/web/server/HttpRouter.hpp" #include "oatpp/network/Server.hpp" #include "oatpp/network/ConnectionProvider.hpp" #include "oatpp/core/macro/component.hpp" #include <list> #include <chrono> #include <mutex> #include <condition_variable> #include <thread> namespace oatpp { namespace test { namespace web { /** * Helper class to run Client-Server tests */ class ClientServerTestRunner { public: typedef oatpp::web::server::HttpRouter HttpRouter; typedef oatpp::web::server::api::ApiController ApiController; private: std::shared_ptr<oatpp::network::Server> m_server; std::list<std::shared_ptr<ApiController>> m_controllers; OATPP_COMPONENT(std::shared_ptr<HttpRouter>, m_router); OATPP_COMPONENT(std::shared_ptr<oatpp::network::ServerConnectionProvider>, m_connectionProvider); OATPP_COMPONENT(std::shared_ptr<oatpp::network::ConnectionHandler>, m_connectionHandler); public: std::shared_ptr<HttpRouter> getRouter() { return m_router; } /** * Add controller's endpoints to router * @param controller */ void addController(const std::shared_ptr<ApiController>& controller) { m_router->route(controller->getEndpoints()); m_controllers.push_back(controller); } std::shared_ptr<oatpp::network::Server> getServer() { return m_server; } /** * Start server, execute code block passed as lambda, stop server. * @tparam Lambda * @param lambda * @param timeout */ template<typename Lambda> void run( const Lambda& lambda, const std::chrono::duration<v_int64, std::micro>& timeout = std::chrono::hours(12) ) { auto startTime = std::chrono::system_clock::now(); std::atomic<bool> running(true); std::mutex timeoutMutex; std::condition_variable timeoutCondition; bool runConditionForLambda = true; m_server = std::make_shared<oatpp::network::Server>(m_connectionProvider, m_connectionHandler); OATPP_LOGD("\033[1;34mClientServerTestRunner\033[0m", "\033[1;34mRunning server on port %s. Timeout %lld(micro)\033[0m", m_connectionProvider->getProperty("port").toString()->c_str(), timeout.count()); std::function<bool()> condition = [&runConditionForLambda](){ return runConditionForLambda; }; std::thread serverThread([&condition, this]{ m_server->run(condition); }); std::thread clientThread([&runConditionForLambda, this, &lambda]{ lambda(); // m_server->stop(); runConditionForLambda = false; m_connectionHandler->stop(); m_connectionProvider->stop(); }); std::thread timerThread([&timeout, &startTime, &running, &timeoutMutex, &timeoutCondition]{ std::unique_lock<std::mutex> lock(timeoutMutex); while(running) { timeoutCondition.wait_for(lock, std::chrono::seconds(1)); auto elapsed = std::chrono::system_clock::now() - startTime; OATPP_ASSERT("ClientServerTestRunner: Error. Timeout." && elapsed < timeout); } }); serverThread.join(); clientThread.join(); auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now() - startTime); OATPP_LOGD("\033[1;34mClientServerTestRunner\033[0m", "\033[1;34mFinished with time %lld(micro). Stopping server...\033[0m", elapsed.count()); running = false; timeoutCondition.notify_one(); timerThread.join(); } }; }}} #endif //oatpp_test_web_ClientServerTestRunner_hpp
vincent-in-black-sesame/oat
src/oatpp-test/web/ClientServerTestRunner.hpp
C++
apache-2.0
4,611
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "CRC.hpp" namespace oatpp { namespace algorithm { const p_uint32 CRC32::TABLE_04C11DB7 = generateTable(0x04C11DB7); v_uint32 CRC32::bitReverse(v_uint32 poly) { v_uint32 result = 0; for(v_int32 i = 0; i < 32; i ++) { if((poly & (1 << i)) > 0) { result |= 1 << (31 - i); } } return result; } p_uint32 CRC32::generateTable(v_uint32 poly) { p_uint32 result = new v_uint32[256]; v_uint32 polyReverse = bitReverse(poly); v_uint32 value; for(v_int32 i = 0; i < 256; i++) { value = i; for (v_int32 bit = 0; bit < 8; bit++) { if (value & 1) { value = (value >> 1) ^ polyReverse; } else { value = (value >> 1); } } result[i] = value; } return result; } v_uint32 CRC32::calc(const void *buffer, v_buff_size size, v_uint32 crc, v_uint32 initValue, v_uint32 xorOut, p_uint32 table) { p_uint8 data = (p_uint8) buffer; crc = crc ^ initValue; for(v_buff_size i = 0; i < size; i++) { crc = table[(crc & 0xFF) ^ data[i]] ^ (crc >> 8); } return crc ^ xorOut; } }}
vincent-in-black-sesame/oat
src/oatpp/algorithm/CRC.cpp
C++
apache-2.0
2,095
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_algorithm_CRC_hpp #define oatpp_algorithm_CRC_hpp #include "oatpp/core/base/Environment.hpp" #include "oatpp/encoding/Hex.hpp" namespace oatpp { namespace algorithm { /** * Implementation of CRC-32. Cyclic redundancy check algorithm. */ class CRC32 { public: /** * Precalculated table */ static const p_uint32 TABLE_04C11DB7; public: static v_uint32 bitReverse(v_uint32 poly); /** * Generates v_uint32 table[256] for polynomial */ static p_uint32 generateTable(v_uint32 poly); /** * Calculate CRC32 value for buffer of defined size * @param buffer * @param size * @param crc * @param initValue * @param xorOut * @param table * @return - CRC32 value (v_uint32) */ static v_uint32 calc(const void *buffer, v_buff_size size, v_uint32 crc = 0, v_uint32 initValue = 0xFFFFFFFF, v_uint32 xorOut = 0xFFFFFFFF, p_uint32 table = TABLE_04C11DB7); }; }} #endif /* oatpp_algorithm_CRC_hpp */
vincent-in-black-sesame/oat
src/oatpp/algorithm/CRC.hpp
C++
apache-2.0
1,965
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /**[info] * This file contains "defines" for ApiClient code generating macro. <br> * Usage:<br> * * ```cpp * #include OATPP_CODEGEN_BEGIN(ApiClient) * ... * // Generated API-Calls. * ... * #include OATPP_CODEGEN_END(ApiClient) * ``` * * * *For details see:* * <ul> * <li>[ApiClient component](https://oatpp.io/docs/components/api-client/)</li> * <li>&id:oatpp::web::client::ApiClient;</li> * </ul> */ #include "oatpp/core/macro/basic.hpp" #include "oatpp/core/macro/codegen.hpp" #define OATPP_MACRO_API_CLIENT_PARAM_MACRO(MACRO, TYPE, PARAM_LIST) MACRO(TYPE, PARAM_LIST) #define OATPP_MACRO_API_CLIENT_PARAM_TYPE(MACRO, TYPE, PARAM_LIST) const TYPE& #define OATPP_MACRO_API_CLIENT_PARAM_NAME(MACRO, TYPE, PARAM_LIST) OATPP_MACRO_FIRSTARG PARAM_LIST #define OATPP_MACRO_API_CLIENT_PARAM_TYPE_STR(MACRO, TYPE, PARAM_LIST) #TYPE #define OATPP_MACRO_API_CLIENT_PARAM_NAME_STR(MACRO, TYPE, PARAM_LIST) OATPP_MACRO_FIRSTARG_STR PARAM_LIST #define OATPP_MACRO_API_CLIENT_PARAM(MACRO, TYPE, PARAM_LIST) (MACRO, TYPE, PARAM_LIST) #define HEADER(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_HEADER, TYPE, (__VA_ARGS__)) #define PATH(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_PATH, TYPE, (__VA_ARGS__)) #define QUERY(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_QUERY, TYPE, (__VA_ARGS__)) #define BODY(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_BODY, TYPE, (__VA_ARGS__)) #define BODY_DTO(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_BODY_DTO, TYPE, (__VA_ARGS__)) #define BODY_STRING(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_BODY_STRING, TYPE, (__VA_ARGS__)) #define AUTHORIZATION(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_AUTHORIZATION, TYPE, (__VA_ARGS__)) #define AUTHORIZATION_BASIC(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_AUTHORIZATION_BASIC, TYPE, (__VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// #define OATPP_MACRO_API_CLIENT_MACRO_SELECTOR(MACRO, TYPE, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_SELECTOR(MACRO, (__VA_ARGS__)) (TYPE, __VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// // INIT /** * Codegen macro to be used in classes extending &id:oatpp::web::client::ApiClient; to generate required fields/methods/constructors for ApiClient. * @param NAME - name of the ApiClient class. */ #define API_CLIENT_INIT(NAME) \ public: \ NAME(const std::shared_ptr<oatpp::web::client::RequestExecutor>& requestExecutor, \ const std::shared_ptr<oatpp::data::mapping::ObjectMapper>& objectMapper) \ : oatpp::web::client::ApiClient(requestExecutor, objectMapper) \ {} \ public: \ static std::shared_ptr<NAME> createShared(const std::shared_ptr<oatpp::web::client::RequestExecutor>& requestExecutor, \ const std::shared_ptr<oatpp::data::mapping::ObjectMapper>& objectMapper){ \ return std::make_shared<NAME>(requestExecutor, objectMapper); \ } // HEADER MACRO #define OATPP_MACRO_API_CLIENT_HEADER_1(TYPE, NAME) \ __headers.put_LockFree(#NAME, ApiClient::TypeInterpretation<TYPE>::toString(#TYPE, NAME)); #define OATPP_MACRO_API_CLIENT_HEADER_2(TYPE, NAME, QUALIFIER) \ __headers.put_LockFree(QUALIFIER, ApiClient::TypeInterpretation<TYPE>::toString(#TYPE, NAME)); #define OATPP_MACRO_API_CLIENT_HEADER(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CLIENT_MACRO_SELECTOR(OATPP_MACRO_API_CLIENT_HEADER_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // PATH MACRO #define OATPP_MACRO_API_CLIENT_PATH_1(TYPE, NAME) \ __pathParams.insert({#NAME, ApiClient::TypeInterpretation<TYPE>::toString(#TYPE, NAME)}); #define OATPP_MACRO_API_CLIENT_PATH_2(TYPE, NAME, QUALIFIER) \ __pathParams.insert({QUALIFIER, ApiClient::TypeInterpretation<TYPE>::toString(#TYPE, NAME)}); #define OATPP_MACRO_API_CLIENT_PATH(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CLIENT_MACRO_SELECTOR(OATPP_MACRO_API_CLIENT_PATH_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // QUERY MACRO #define OATPP_MACRO_API_CLIENT_QUERY_1(TYPE, NAME) \ __queryParams.insert({#NAME, ApiClient::TypeInterpretation<TYPE>::toString(#TYPE, NAME)}); #define OATPP_MACRO_API_CLIENT_QUERY_2(TYPE, NAME, QUALIFIER) \ __queryParams.insert({QUALIFIER, ApiClient::TypeInterpretation<TYPE>::toString(#TYPE, NAME)}); #define OATPP_MACRO_API_CLIENT_QUERY(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CLIENT_MACRO_SELECTOR(OATPP_MACRO_API_CLIENT_QUERY_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // BODY MACRO #define OATPP_MACRO_API_CLIENT_BODY(TYPE, PARAM_LIST) \ __body = OATPP_MACRO_FIRSTARG PARAM_LIST; // BODY_DTO MACRO #define OATPP_MACRO_API_CLIENT_BODY_DTO(TYPE, PARAM_LIST) \ __body = oatpp::web::protocol::http::outgoing::BufferBody::createShared( \ m_objectMapper->writeToString(OATPP_MACRO_FIRSTARG PARAM_LIST), \ m_objectMapper->getInfo().http_content_type \ ); // BODY_STRING MACRO #define OATPP_MACRO_API_CLIENT_BODY_STRING(TYPE, PARAM_LIST) \ __body = oatpp::web::protocol::http::outgoing::BufferBody::createShared(OATPP_MACRO_FIRSTARG PARAM_LIST); // AUTHORIZATION MACRO #define OATPP_MACRO_API_CLIENT_AUTHORIZATION_2(TYPE, TOKEN, SCHEME) \ __headers.put_LockFree("Authorization", String(SCHEME " ") + String(TOKEN)); #define OATPP_MACRO_API_CLIENT_AUTHORIZATION(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CLIENT_MACRO_SELECTOR(OATPP_MACRO_API_CLIENT_AUTHORIZATION_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // AUTHORIZATION_BASIC MACRO #define OATPP_MACRO_API_CLIENT_AUTHORIZATION_BASIC_1(TYPE, TOKEN) \ __headers.put_LockFree("Authorization", String("Basic ") + oatpp::encoding::Base64::encode(TOKEN)); #define OATPP_MACRO_API_CLIENT_AUTHORIZATION_BASIC(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CLIENT_MACRO_SELECTOR(OATPP_MACRO_API_CLIENT_AUTHORIZATION_BASIC_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // FOR EACH #define OATPP_MACRO_API_CLIENT_PARAM_DECL(INDEX, COUNT, X) \ OATPP_MACRO_API_CLIENT_PARAM_TYPE X OATPP_MACRO_API_CLIENT_PARAM_NAME X, #define OATPP_MACRO_API_CLIENT_PARAM_PUT(INDEX, COUNT, X) \ OATPP_MACRO_API_CLIENT_PARAM_MACRO X // API_CALL MACRO #define OATPP_API_CALL_0(NAME, METHOD, PATH) \ const oatpp::data::share::StringTemplate Z_PATH_TEMPLATE_##NAME = parsePathTemplate(#NAME, PATH); \ \ static void Z_ADD_HEADERS_##NAME(oatpp::web::client::ApiClient::Headers& headers, ...) { \ (void) headers; \ } \ \ std::shared_ptr<oatpp::web::protocol::http::incoming::Response> NAME( \ const std::shared_ptr<oatpp::web::client::RequestExecutor::ConnectionHandle>& __connectionHandle = nullptr \ ) { \ oatpp::web::client::ApiClient::Headers __headers; \ Z_ADD_HEADERS_##NAME(__headers, 1); \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Body> body; \ return executeRequest(METHOD, \ Z_PATH_TEMPLATE_##NAME, \ __headers, \ {}, \ {}, \ body, \ __connectionHandle); \ } #define OATPP_API_CALL_1(NAME, METHOD, PATH, ...) \ const oatpp::data::share::StringTemplate Z_PATH_TEMPLATE_##NAME = parsePathTemplate(#NAME, PATH); \ \ static void Z_ADD_HEADERS_##NAME(oatpp::web::client::ApiClient::Headers& headers, ...) { \ (void) headers; \ } \ \ std::shared_ptr<oatpp::web::protocol::http::incoming::Response> NAME(\ OATPP_MACRO_FOREACH(OATPP_MACRO_API_CLIENT_PARAM_DECL, __VA_ARGS__) \ const std::shared_ptr<oatpp::web::client::RequestExecutor::ConnectionHandle>& __connectionHandle = nullptr \ ) { \ oatpp::web::client::ApiClient::Headers __headers; \ Z_ADD_HEADERS_##NAME(__headers, 1); \ std::unordered_map<oatpp::String, oatpp::String> __pathParams; \ std::unordered_map<oatpp::String, oatpp::String> __queryParams; \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Body> __body; \ OATPP_MACRO_FOREACH(OATPP_MACRO_API_CLIENT_PARAM_PUT, __VA_ARGS__) \ return executeRequest(METHOD, \ Z_PATH_TEMPLATE_##NAME, \ __headers, \ __pathParams, \ __queryParams, \ __body, \ __connectionHandle); \ } // Chooser #define OATPP_API_CALL_MACRO_0(METHOD, PATH, NAME) \ OATPP_API_CALL_0(NAME, METHOD, PATH) #define OATPP_API_CALL_MACRO_1(METHOD, PATH, NAME, ...) \ OATPP_API_CALL_1(NAME, METHOD, PATH, __VA_ARGS__) /** * Codegen macro to be used in `oatpp::web::client::ApiClient` to generate REST API-Calls. * @param METHOD - Http method ("GET", "POST", "PUT", etc.) * @param PATH - Path to endpoint (without host) * @param NAME - Name of the generated method * @return - std::shared_ptr to &id:oatpp::web::protocol::http::incoming::Response; */ #define API_CALL(METHOD, PATH, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_API_CALL_MACRO_, (__VA_ARGS__)) (METHOD, PATH, __VA_ARGS__)) // API_CALL_ASYNC MACRO #define OATPP_API_CALL_ASYNC_0(NAME, METHOD, PATH) \ const oatpp::data::share::StringTemplate Z_PATH_TEMPLATE_##NAME = parsePathTemplate(#NAME, PATH); \ \ static void Z_ADD_HEADERS_##NAME(oatpp::web::client::ApiClient::Headers& headers, ...) { \ (void) headers; \ } \ \ oatpp::async::CoroutineStarterForResult<const std::shared_ptr<oatpp::web::protocol::http::incoming::Response>&> NAME( \ const std::shared_ptr<oatpp::web::client::RequestExecutor::ConnectionHandle>& __connectionHandle = nullptr \ ) { \ oatpp::web::client::ApiClient::Headers __headers; \ Z_ADD_HEADERS_##NAME(__headers, 1); \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Body> body; \ return executeRequestAsync(METHOD, \ Z_PATH_TEMPLATE_##NAME, \ __headers, \ {}, \ {}, \ body, \ __connectionHandle); \ } #define OATPP_API_CALL_ASYNC_1(NAME, METHOD, PATH, ...) \ const oatpp::data::share::StringTemplate Z_PATH_TEMPLATE_##NAME = parsePathTemplate(#NAME, PATH); \ \ static void Z_ADD_HEADERS_##NAME(oatpp::web::client::ApiClient::Headers& headers, ...) { \ (void) headers; \ } \ \ oatpp::async::CoroutineStarterForResult<const std::shared_ptr<oatpp::web::protocol::http::incoming::Response>&> NAME(\ OATPP_MACRO_FOREACH(OATPP_MACRO_API_CLIENT_PARAM_DECL, __VA_ARGS__) \ const std::shared_ptr<oatpp::web::client::RequestExecutor::ConnectionHandle>& __connectionHandle = nullptr \ ) { \ oatpp::web::client::ApiClient::Headers __headers; \ Z_ADD_HEADERS_##NAME(__headers, 1); \ std::unordered_map<oatpp::String, oatpp::String> __pathParams; \ std::unordered_map<oatpp::String, oatpp::String> __queryParams; \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Body> __body; \ OATPP_MACRO_FOREACH(OATPP_MACRO_API_CLIENT_PARAM_PUT, __VA_ARGS__) \ return executeRequestAsync(METHOD, \ Z_PATH_TEMPLATE_##NAME, \ __headers, \ __pathParams, \ __queryParams, \ __body, \ __connectionHandle); \ } #define OATPP_API_CALL_ASYNC_MACRO_0(METHOD, PATH, NAME) \ OATPP_API_CALL_ASYNC_0(NAME, METHOD, PATH) #define OATPP_API_CALL_ASYNC_MACRO_1(METHOD, PATH, NAME, ...) \ OATPP_API_CALL_ASYNC_1(NAME, METHOD, PATH, __VA_ARGS__) /** * Codegen macro to be used in `oatpp::web::client::ApiClient` to generate Asynchronous REST API-Calls. * @param METHOD - Http method ("GET", "POST", "PUT", etc.) * @param PATH - Path to endpoint (without host) * @param NAME - Name of the generated method * @return - &id:oatpp::async::CoroutineStarterForResult;<const std::shared_ptr<&id:oatpp::web::protocol::http::incoming::Response;>&>. */ #define API_CALL_ASYNC(METHOD, PATH, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_API_CALL_ASYNC_MACRO_, (__VA_ARGS__)) (METHOD, PATH, __VA_ARGS__)) /** * Codegen macro to add default headers to API_CALL */ #define API_CALL_HEADERS(NAME) \ \ static void Z_ADD_HEADERS_##NAME(oatpp::web::client::ApiClient::Headers& headers, int) { \ Z_ADD_HEADERS_##NAME(headers); /* call first method */ \ Z_ADD_DEFAULT_HEADERS_##NAME(headers); \ } \ \ static void Z_ADD_DEFAULT_HEADERS_##NAME(oatpp::web::client::ApiClient::Headers& headers)
vincent-in-black-sesame/oat
src/oatpp/codegen/ApiClient_define.hpp
C++
apache-2.0
13,479
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /**[info] * This file contains "undefs" for ApiClient code generating macro. <br> * Usage:<br> * * ```cpp * #include OATPP_CODEGEN_BEGIN(ApiClient) * ... * // Generated API-Calls. * ... * #include OATPP_CODEGEN_END(ApiClient) * ``` * * * *For details see:* * <ul> * <li>[ApiClient component](https://oatpp.io/docs/components/api-client/)</li> * <li>&id:oatpp::web::client::ApiClient;</li> * </ul> */ #undef OATPP_MACRO_API_CLIENT_PARAM_MACRO #undef OATPP_MACRO_API_CLIENT_PARAM_TYPE #undef OATPP_MACRO_API_CLIENT_PARAM_NAME #undef OATPP_MACRO_API_CLIENT_PARAM_TYPE_STR #undef OATPP_MACRO_API_CLIENT_PARAM_NAME_STR #undef OATPP_MACRO_API_CLIENT_PARAM #undef HEADER #undef PATH #undef QUERY #undef BODY #undef BODY_DTO #undef BODY_STRING #undef AUTHORIZATION #undef AUTHORIZATION_BASIC // #undef OATPP_MACRO_API_CLIENT_MACRO_SELECTOR // INIT #undef API_CLIENT_INIT // HEADER MACRO #undef OATPP_MACRO_API_CLIENT_HEADER_1 #undef OATPP_MACRO_API_CLIENT_HEADER_2 #undef OATPP_MACRO_API_CLIENT_HEADER // PATH MACRO #undef OATPP_MACRO_API_CLIENT_PATH_1 #undef OATPP_MACRO_API_CLIENT_PATH_2 #undef OATPP_MACRO_API_CLIENT_PATH // QUERY MACRO #undef OATPP_MACRO_API_CLIENT_QUERY_1 #undef OATPP_MACRO_API_CLIENT_QUERY_2 #undef OATPP_MACRO_API_CLIENT_QUERY // BODY MACRO #undef OATPP_MACRO_API_CLIENT_BODY // BODY_DTO MACRO #undef OATPP_MACRO_API_CLIENT_BODY_DTO // BODY_STRING MACRO #undef OATPP_MACRO_API_CLIENT_BODY_STRING // AUTHORIZATION MACRO #undef OATPP_MACRO_API_CLIENT_AUTHORIZATION_2 #undef OATPP_MACRO_API_CLIENT_AUTHORIZATION // AUTHORIZATION_BASIC MACRO #undef OATPP_MACRO_API_CLIENT_AUTHORIZATION_BASIC_1 #undef OATPP_MACRO_API_CLIENT_AUTHORIZATION_BASIC // FOR EACH #undef OATPP_MACRO_API_CLIENT_PARAM_DECL #undef OATPP_MACRO_API_CLIENT_PARAM_PUT // API_CALL MACRO #undef OATPP_API_CALL_0 #undef OATPP_API_CALL_1 #undef OATPP_API_CALL_MACRO_0 #undef OATPP_API_CALL_MACRO_1 #undef API_CALL // API_CALL_ASYNC MACRO #undef OATPP_API_CALL_ASYNC_0 #undef OATPP_API_CALL_ASYNC_1 #undef OATPP_API_CALL_ASYNC_MACRO_0 #undef OATPP_API_CALL_ASYNC_MACRO_1 #undef API_CALL_ASYNC #undef API_CALL_HEADERS
vincent-in-black-sesame/oat
src/oatpp/codegen/ApiClient_undef.hpp
C++
apache-2.0
3,149
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /**[info] * This file contains "defines" for ApiController code generating macro. <br> * Usage:<br> * * ```cpp * #include OATPP_CODEGEN_BEGIN(ApiController) * ... * // Generated Endpoints. * ... * #include OATPP_CODEGEN_END(ApiController) * ``` * * * *For details see:* * <ul> * <li>[ApiController component](https://oatpp.io/docs/components/api-controller/)</li> * <li>&id:oatpp::web::server::api::ApiController;</li> * </ul> */ #include "oatpp/core/macro/basic.hpp" #include "oatpp/core/macro/codegen.hpp" #include "./api_controller/base_define.hpp" #include "./api_controller/auth_define.hpp" #include "./api_controller/bundle_define.hpp" #include "./api_controller/cors_define.hpp"
vincent-in-black-sesame/oat
src/oatpp/codegen/ApiController_define.hpp
C++
apache-2.0
1,706
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /**[info] * This file contains "undefs" for ApiController code generating macro. <br> * Usage:<br> * * ```cpp * #include OATPP_CODEGEN_BEGIN(ApiController) * ... * // Generated Endpoints. * ... * #include OATPP_CODEGEN_END(ApiController) * ``` * * * *For details see:* * <ul> * <li>[ApiController component](https://oatpp.io/docs/components/api-controller/)</li> * <li>&id:oatpp::web::server::api::ApiController;</li> * </ul> */ #include "./api_controller/base_undef.hpp" #include "./api_controller/auth_undef.hpp" #include "./api_controller/bundle_undef.hpp" #include "./api_controller/cors_undef.hpp"
vincent-in-black-sesame/oat
src/oatpp/codegen/ApiController_undef.hpp
C++
apache-2.0
1,622
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /**[info] * This file contains "defines" for DTO code generating macro. <br> * Usage:<br> * * ```cpp * #include OATPP_CODEGEN_BEGIN(DTO) * ... * // Generated Endpoints. * ... * #include OATPP_CODEGEN_END(DTO) * ``` * * * *For details see:* * <ul> * <li>[Data Transfer Object(DTO) component](https://oatpp.io/docs/components/dto/)</li> * <li>&id:oatpp::data::mapping::type::Object;</li> * </ul> */ #include "oatpp/core/macro/basic.hpp" #include "oatpp/core/macro/codegen.hpp" #include "./dto/base_define.hpp" #include "./dto/enum_define.hpp"
vincent-in-black-sesame/oat
src/oatpp/codegen/DTO_define.hpp
C++
apache-2.0
1,561
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /**[info] * This file contains "undefs" for DTO code generating macro. <br> * Usage:<br> * * ```cpp * #include OATPP_CODEGEN_BEGIN(DTO) * ... * // Generated Endpoints. * ... * #include OATPP_CODEGEN_END(DTO) * ``` * * * *For details see:* * <ul> * <li>[Data Transfer Object(DTO) component](https://oatpp.io/docs/components/dto/)</li> * <li>&id:oatpp::data::mapping::type::Object;</li> * </ul> */ #include "./dto/base_undef.hpp" #include "./dto/enum_undef.hpp"
vincent-in-black-sesame/oat
src/oatpp/codegen/DTO_undef.hpp
C++
apache-2.0
1,479
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "oatpp/core/macro/basic.hpp" #include "oatpp/core/macro/codegen.hpp" #define OATPP_MACRO_DB_CLIENT_PARAM_TYPE(MACRO, TYPE, PARAM_LIST) TYPE #define OATPP_MACRO_DB_CLIENT_PARAM_NAME(MACRO, TYPE, PARAM_LIST) OATPP_MACRO_FIRSTARG PARAM_LIST #define OATPP_MACRO_DB_CLIENT_PARAM_TYPE_STR(MACRO, TYPE, PARAM_LIST) #TYPE #define OATPP_MACRO_DB_CLIENT_PARAM_NAME_STR(MACRO, TYPE, PARAM_LIST) OATPP_MACRO_FIRSTARG_STR PARAM_LIST #define OATPP_MACRO_DB_CLIENT_PARAM_MACRO(MACRO, TYPE, PARAM_LIST) MACRO(TYPE, PARAM_LIST) #define OATPP_MACRO_DB_CLIENT_PREPARE_MACRO(MACRO, VAL) MACRO(VAL) #define OATPP_MACRO_DB_CLIENT_PARAM_MACRO_TYPE(MACRO, TYPE, PARAM_LIST) MACRO ##_TYPE(TYPE, PARAM_LIST) #define OATPP_MACRO_DB_CLIENT_PARAM(MACRO, TYPE, PARAM_LIST) (MACRO, TYPE, PARAM_LIST) #define OATPP_MACRO_DB_CLIENT_PREPARE(MACRO, VAL) (MACRO, VAL) #define PARAM(TYPE, ...) OATPP_MACRO_DB_CLIENT_PARAM(OATPP_MACRO_DB_CLIENT_PARAM_PARAM, TYPE, (__VA_ARGS__)) #define PREPARE(VAL) OATPP_MACRO_DB_CLIENT_PREPARE(OATPP_MACRO_DB_CLIENT_PARAM_PREPARE, VAL) ////////////////////////////////////////////////////////////////////////// #define OATPP_MACRO_DB_CLIENT_MACRO_SELECTOR(MACRO, TYPE, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_SELECTOR(MACRO, (__VA_ARGS__)) (TYPE, __VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// // PARAM MACRO USE-CASE #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_PUT_DECL(X) \ const OATPP_MACRO_DB_CLIENT_PARAM_TYPE X & OATPP_MACRO_DB_CLIENT_PARAM_NAME X, #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_PUT_TYPE(X) \ OATPP_MACRO_DB_CLIENT_PARAM_MACRO_TYPE X #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_PUT_BODY(X) \ OATPP_MACRO_DB_CLIENT_PARAM_MACRO X // PARAM MACRO #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_1(TYPE, NAME) \ __params.insert({#NAME, NAME}); #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_2(TYPE, NAME, QUALIFIER) \ __params.insert({QUALIFIER, NAME}); #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM(TYPE, PARAM_LIST) \ OATPP_MACRO_DB_CLIENT_MACRO_SELECTOR(OATPP_MACRO_DB_CLIENT_PARAM_PARAM_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // PARAM_TYPE MACRO #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE_1(TYPE, NAME) \ map.insert({#NAME, TYPE::Class::getType()}); #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE_2(TYPE, NAME, QUALIFIER) \ map.insert({QUALIFIER, TYPE::Class::getType()}); #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE(TYPE, PARAM_LIST) \ OATPP_MACRO_DB_CLIENT_MACRO_SELECTOR(OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // PREPARE MACRO USE-CASE #define OATPP_MACRO_DB_CLIENT_PARAM_PREPARE_PUT_DECL(X) #define OATPP_MACRO_DB_CLIENT_PARAM_PREPARE_PUT_TYPE(X) \ OATPP_MACRO_DB_CLIENT_PREPARE_MACRO X #define OATPP_MACRO_DB_CLIENT_PARAM_PREPARE_PUT_BODY(X) // PREPARE MACRO #define OATPP_MACRO_DB_CLIENT_PARAM_PREPARE(VAL) \ __prepare = VAL; // PARAMS USE-CASE #define OATPP_MACRO_PARAM_USECASE_DECL(MACRO, ...) MACRO ## _PUT_DECL((MACRO, __VA_ARGS__)) #define OATPP_MACRO_PARAM_USECASE_TYPE(MACRO, ...) MACRO ## _PUT_TYPE((MACRO, __VA_ARGS__)) #define OATPP_MACRO_PARAM_USECASE_BODY(MACRO, ...) MACRO ## _PUT_BODY((MACRO, __VA_ARGS__)) // FOR EACH #define OATPP_MACRO_DB_CLIENT_PARAM_PUT_DECL(INDEX, COUNT, X) \ OATPP_MACRO_PARAM_USECASE_DECL X #define OATPP_MACRO_DB_CLIENT_PARAM_PUT_TYPE(INDEX, COUNT, X) \ OATPP_MACRO_PARAM_USECASE_TYPE X #define OATPP_MACRO_DB_CLIENT_PARAM_PUT(INDEX, COUNT, X) \ OATPP_MACRO_PARAM_USECASE_BODY X // QUERY MACRO #define OATPP_QUERY_0(NAME, QUERY_TEXT) \ const oatpp::data::share::StringTemplate Z_QUERY_TEMPLATE_##NAME = \ this->parseQueryTemplate(#NAME, QUERY_TEXT, {}, false); \ \ std::shared_ptr<oatpp::orm::QueryResult> NAME(const oatpp::provider::ResourceHandle<oatpp::orm::Connection>& connection = nullptr) { \ std::unordered_map<oatpp::String, oatpp::Void> __params; \ return this->execute(Z_QUERY_TEMPLATE_##NAME, __params, connection); \ } #define OATPP_QUERY_1(NAME, QUERY_TEXT, ...) \ \ oatpp::data::share::StringTemplate Z_QUERY_TEMPLATE_CREATOR_##NAME() { \ bool __prepare = false; \ oatpp::orm::Executor::ParamsTypeMap map; \ \ OATPP_MACRO_FOREACH(OATPP_MACRO_DB_CLIENT_PARAM_PUT_TYPE, __VA_ARGS__) \ \ return this->parseQueryTemplate(#NAME, QUERY_TEXT, map, __prepare); \ } \ \ const oatpp::data::share::StringTemplate Z_QUERY_TEMPLATE_##NAME = Z_QUERY_TEMPLATE_CREATOR_##NAME(); \ \ std::shared_ptr<oatpp::orm::QueryResult> NAME( \ OATPP_MACRO_FOREACH(OATPP_MACRO_DB_CLIENT_PARAM_PUT_DECL, __VA_ARGS__) \ const oatpp::provider::ResourceHandle<oatpp::orm::Connection>& connection = nullptr \ ) { \ std::unordered_map<oatpp::String, oatpp::Void> __params; \ OATPP_MACRO_FOREACH(OATPP_MACRO_DB_CLIENT_PARAM_PUT, __VA_ARGS__) \ return this->execute(Z_QUERY_TEMPLATE_##NAME, __params, connection); \ } // Chooser #define OATPP_QUERY_MACRO_0(NAME, QUERY_TEXT) \ OATPP_QUERY_0(NAME, QUERY_TEXT) #define OATPP_QUERY_MACRO_1(NAME, QUERY_TEXT, ...) \ OATPP_QUERY_1(NAME, QUERY_TEXT, __VA_ARGS__) #define QUERY(NAME, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_QUERY_MACRO_, (__VA_ARGS__)) (NAME, __VA_ARGS__))
vincent-in-black-sesame/oat
src/oatpp/codegen/DbClient_define.hpp
C++
apache-2.0
6,164
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #undef OATPP_MACRO_DB_CLIENT_PARAM_TYPE #undef OATPP_MACRO_DB_CLIENT_PARAM_NAME #undef OATPP_MACRO_DB_CLIENT_PARAM_TYPE_STR #undef OATPP_MACRO_DB_CLIENT_PARAM_NAME_STR #undef OATPP_MACRO_DB_CLIENT_PARAM_MACRO #undef OATPP_MACRO_DB_CLIENT_PREPARE_MACRO #undef OATPP_MACRO_DB_CLIENT_PARAM_MACRO_TYPE #undef OATPP_MACRO_DB_CLIENT_PARAM #undef OATPP_MACRO_DB_CLIENT_PREPARE #undef PARAM #undef PREPARE ////////////////////////////////////////////////////////////////////////// #undef OATPP_MACRO_DB_CLIENT_MACRO_SELECTOR ////////////////////////////////////////////////////////////////////////// // PARAM MACRO USE-CASE #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_PUT_DECL #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_PUT_TYPE #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_PUT_BODY // PARAM MACRO #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_1 #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_2 #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM // PARAM_TYPE MACRO #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE_1 #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE_2 #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE // PREPARE MACRO USE-CASE #undef OATPP_MACRO_DB_CLIENT_PARAM_PREPARE_PUT_DECL #undef OATPP_MACRO_DB_CLIENT_PARAM_PREPARE_PUT_TYPE #undef OATPP_MACRO_DB_CLIENT_PARAM_PREPARE_PUT_BODY // PREPARE MACRO #undef OATPP_MACRO_DB_CLIENT_PARAM_PREPARE // PARAMS USE-CASE #undef OATPP_MACRO_PARAM_USECASE_DECL #undef OATPP_MACRO_PARAM_USECASE_TYPE #undef OATPP_MACRO_PARAM_USECASE_BODY // FOR EACH #undef OATPP_MACRO_DB_CLIENT_PARAM_PUT_DECL #undef OATPP_MACRO_DB_CLIENT_PARAM_PUT_TYPE #undef OATPP_MACRO_DB_CLIENT_PARAM_PUT // QUERY MACRO #undef OATPP_QUERY_0 #undef OATPP_QUERY_1 // Chooser #undef OATPP_QUERY_MACRO_0 #undef OATPP_QUERY_MACRO_1 #undef QUERY
vincent-in-black-sesame/oat
src/oatpp/codegen/DbClient_undef.hpp
C++
apache-2.0
2,755
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #define AUTHORIZATION(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_AUTHORIZATION, OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO, TYPE, (__VA_ARGS__)) // AUTHORIZATION MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_1(TYPE, NAME) \ auto __param_str_val_##NAME = __request->getHeader(oatpp::web::protocol::http::Header::AUTHORIZATION); \ std::shared_ptr<oatpp::web::server::handler::AuthorizationObject> __param_aosp_val_##NAME = ApiController::handleDefaultAuthorization(__param_str_val_##NAME); \ TYPE NAME = std::static_pointer_cast<TYPE::element_type>(__param_aosp_val_##NAME); #define OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_2(TYPE, NAME, AUTH_HANDLER) \ auto __param_str_val_##NAME = __request->getHeader(oatpp::web::protocol::http::Header::AUTHORIZATION); \ std::shared_ptr<oatpp::web::server::handler::AuthorizationHandler> __auth_handler_##NAME = AUTH_HANDLER; \ std::shared_ptr<oatpp::web::server::handler::AuthorizationObject> __param_aosp_val_##NAME = __auth_handler_##NAME->handleAuthorization(__param_str_val_##NAME); \ TYPE NAME = std::static_pointer_cast<TYPE::element_type>(__param_aosp_val_##NAME); #define OATPP_MACRO_API_CONTROLLER_AUTHORIZATION(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // __INFO #define OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO_1(TYPE, NAME) \ auto __param_obj_##NAME = ApiController::getDefaultAuthorizationHandler(); \ if(__param_obj_##NAME) { \ info->headers.add(oatpp::web::protocol::http::Header::AUTHORIZATION, oatpp::String::Class::getType()); \ info->headers[oatpp::web::protocol::http::Header::AUTHORIZATION].description = __param_obj_##NAME ->getScheme(); \ info->authorization = __param_obj_##NAME ->getScheme(); \ } else { \ throw oatpp::web::protocol::http::HttpError(Status::CODE_500, "No authorization handler set up in controller before controller was added to router or swagger-doc."); \ } #define OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO_2(TYPE, NAME, AUTH_HANDLER) \ std::shared_ptr<oatpp::web::server::handler::AuthorizationHandler> __auth_handler_##NAME = AUTH_HANDLER; \ if(__auth_handler_##NAME) { \ info->headers.add(oatpp::web::protocol::http::Header::AUTHORIZATION, oatpp::String::Class::getType()); \ info->headers[oatpp::web::protocol::http::Header::AUTHORIZATION].description = __auth_handler_##NAME->getScheme(); \ info->authorization = __auth_handler_##NAME->getScheme(); \ } else { \ throw oatpp::web::protocol::http::HttpError(Status::CODE_500, "Invalid authorization handler given (or not set up) in AUTHORIZATION(TYPE, NAME, AUTH_HANDLER) before controller was added to router or swagger-doc."); \ } #define OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST)
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/auth_define.hpp
C++
apache-2.0
4,013
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #undef AUTHORIZATION // AUTHORIZATION MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_1 #undef OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_2 #undef OATPP_MACRO_API_CONTROLLER_AUTHORIZATION // __INFO #undef OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO_1 #undef OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO_2 #undef OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/auth_undef.hpp
C++
apache-2.0
1,421
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #define OATPP_MACRO_API_CONTROLLER_PARAM_MACRO(MACRO, INFO, TYPE, PARAM_LIST) MACRO(TYPE, PARAM_LIST) #define OATPP_MACRO_API_CONTROLLER_PARAM_INFO(MACRO, INFO, TYPE, PARAM_LIST) INFO(TYPE, PARAM_LIST) #define OATPP_MACRO_API_CONTROLLER_PARAM_TYPE(MACRO, INFO, TYPE, PARAM_LIST) const TYPE& #define OATPP_MACRO_API_CONTROLLER_PARAM_NAME(MACRO, INFO, TYPE, PARAM_LIST) OATPP_MACRO_FIRSTARG PARAM_LIST #define OATPP_MACRO_API_CONTROLLER_PARAM_TYPE_STR(MACRO, INFO, TYPE, PARAM_LIST) #TYPE #define OATPP_MACRO_API_CONTROLLER_PARAM_NAME_STR(MACRO, INFO, TYPE, PARAM_LIST) OATPP_MACRO_FIRSTARG_STR PARAM_LIST #define OATPP_MACRO_API_CONTROLLER_PARAM(MACRO, INFO, TYPE, PARAM_LIST) (MACRO, INFO, TYPE, PARAM_LIST) #define REQUEST(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_REQUEST, OATPP_MACRO_API_CONTROLLER_REQUEST_INFO, TYPE, (__VA_ARGS__)) #define HEADER(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_HEADER, OATPP_MACRO_API_CONTROLLER_HEADER_INFO, TYPE, (__VA_ARGS__)) #define PATH(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_PATH, OATPP_MACRO_API_CONTROLLER_PATH_INFO, TYPE, (__VA_ARGS__)) #define QUERIES(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_QUERIES, OATPP_MACRO_API_CONTROLLER_QUERIES_INFO, TYPE, (__VA_ARGS__)) #define QUERY(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_QUERY, OATPP_MACRO_API_CONTROLLER_QUERY_INFO, TYPE, (__VA_ARGS__)) #define BODY_STRING(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_BODY_STRING, OATPP_MACRO_API_CONTROLLER_BODY_STRING_INFO, TYPE, (__VA_ARGS__)) #define BODY_DTO(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_BODY_DTO, OATPP_MACRO_API_CONTROLLER_BODY_DTO_INFO, TYPE, (__VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// #define OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(MACRO, TYPE, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_SELECTOR(MACRO, (__VA_ARGS__)) (TYPE, __VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// // REQUEST MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_REQUEST(TYPE, PARAM_LIST) \ const auto& OATPP_MACRO_FIRSTARG PARAM_LIST = __request; #define OATPP_MACRO_API_CONTROLLER_REQUEST_INFO(TYPE, PARAM_LIST) // HEADER MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_HEADER_1(TYPE, NAME) \ const auto& __param_str_val_##NAME = __request->getHeader(#NAME); \ if(!__param_str_val_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Missing HEADER parameter '" #NAME "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ bool __param_validation_check_##NAME; \ const auto& NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Invalid HEADER parameter '" #NAME "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } #define OATPP_MACRO_API_CONTROLLER_HEADER_2(TYPE, NAME, QUALIFIER) \ const auto& __param_str_val_##NAME = __request->getHeader(QUALIFIER); \ if(!__param_str_val_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, oatpp::String("Missing HEADER parameter '") + QUALIFIER + "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ bool __param_validation_check_##NAME; \ const auto& NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, \ oatpp::String("Invalid HEADER parameter '") + \ QUALIFIER + \ "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } #define OATPP_MACRO_API_CONTROLLER_HEADER(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_HEADER_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // __INFO #define OATPP_MACRO_API_CONTROLLER_HEADER_INFO_1(TYPE, NAME) \ info->headers.add(#NAME, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_HEADER_INFO_2(TYPE, NAME, QUALIFIER) \ info->headers.add(QUALIFIER, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_HEADER_INFO(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_HEADER_INFO_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // PATH MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_PATH_1(TYPE, NAME) \ const auto& __param_str_val_##NAME = __request->getPathVariable(#NAME); \ if(!__param_str_val_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Missing PATH parameter '" #NAME "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ bool __param_validation_check_##NAME; \ const auto& NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Invalid PATH parameter '" #NAME "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } #define OATPP_MACRO_API_CONTROLLER_PATH_2(TYPE, NAME, QUALIFIER) \ const auto& __param_str_val_##NAME = __request->getPathVariable(QUALIFIER); \ if(!__param_str_val_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, \ oatpp::String("Missing PATH parameter '") + QUALIFIER + "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ bool __param_validation_check_##NAME; \ const auto NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, \ oatpp::String("Invalid PATH parameter '") + \ QUALIFIER + \ "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } #define OATPP_MACRO_API_CONTROLLER_PATH(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_PATH_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // __INFO #define OATPP_MACRO_API_CONTROLLER_PATH_INFO_1(TYPE, NAME) \ info->pathParams.add(#NAME, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_PATH_INFO_2(TYPE, NAME, QUALIFIER) \ info->pathParams.add(QUALIFIER, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_PATH_INFO(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_PATH_INFO_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // QUERIES MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_QUERIES(TYPE, PARAM_LIST) \ const auto& OATPP_MACRO_FIRSTARG PARAM_LIST = __request->getQueryParameters(); #define OATPP_MACRO_API_CONTROLLER_QUERIES_INFO(TYPE, PARAM_LIST) // QUERY MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_QUERY_1(TYPE, NAME) \ const auto& __param_str_val_##NAME = __request->getQueryParameter(#NAME); \ if(!__param_str_val_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Missing QUERY parameter '" #NAME "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ bool __param_validation_check_##NAME; \ const auto& NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Invalid QUERY parameter '" #NAME "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } #define OATPP_MACRO_API_CONTROLLER_QUERY_2(TYPE, NAME, QUALIFIER) \ const auto& __param_str_val_##NAME = __request->getQueryParameter(QUALIFIER); \ if(!__param_str_val_##NAME) \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, \ oatpp::String("Missing QUERY parameter '") + QUALIFIER + "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ bool __param_validation_check_##NAME; \ const auto& NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, \ oatpp::String("Invalid QUERY parameter '") + \ QUALIFIER + \ "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } #define OATPP_MACRO_API_CONTROLLER_QUERY_3(TYPE, NAME, QUALIFIER, DEFAULT) \ TYPE NAME = DEFAULT; \ const auto& __param_str_val_##NAME = __request->getQueryParameter(QUALIFIER); \ if(__param_str_val_##NAME) { \ bool __param_validation_check_##NAME; \ NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, \ oatpp::String("Invalid QUERY parameter '") + \ QUALIFIER + \ "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ } #define OATPP_MACRO_API_CONTROLLER_QUERY(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_QUERY_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // __INFO #define OATPP_MACRO_API_CONTROLLER_QUERY_INFO_1(TYPE, NAME) \ info->queryParams.add(#NAME, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_QUERY_INFO_2(TYPE, NAME, QUALIFIER) \ info->queryParams.add(QUALIFIER, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_QUERY_INFO_3(TYPE, NAME, QUALIFIER, DEFAULT) \ info->queryParams.add(QUALIFIER, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_QUERY_INFO(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_QUERY_INFO_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // BODY_STRING MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_BODY_STRING(TYPE, PARAM_LIST) \ const auto& OATPP_MACRO_FIRSTARG PARAM_LIST = __request->readBodyToString(); // __INFO #define OATPP_MACRO_API_CONTROLLER_BODY_STRING_INFO(TYPE, PARAM_LIST) \ info->body.name = OATPP_MACRO_FIRSTARG_STR PARAM_LIST; \ info->body.required = true; \ info->body.type = oatpp::data::mapping::type::__class::String::getType(); \ if(getDefaultObjectMapper()) { \ info->bodyContentType = getDefaultObjectMapper()->getInfo().http_content_type; \ } // BODY_DTO MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_BODY_DTO(TYPE, PARAM_LIST) \ if(!getDefaultObjectMapper()) { \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_500, "ObjectMapper was NOT set. Can't deserialize the request body."); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ const auto& OATPP_MACRO_FIRSTARG PARAM_LIST = \ __request->readBodyToDto<TYPE>(getDefaultObjectMapper().get()); \ if(!OATPP_MACRO_FIRSTARG PARAM_LIST) { \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Missing valid body parameter '" OATPP_MACRO_FIRSTARG_STR PARAM_LIST "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } // __INFO #define OATPP_MACRO_API_CONTROLLER_BODY_DTO_INFO(TYPE, PARAM_LIST) \ info->body.name = OATPP_MACRO_FIRSTARG_STR PARAM_LIST; \ info->body.required = true; \ info->body.type = TYPE::Class::getType(); \ if(getDefaultObjectMapper()) { \ info->bodyContentType = getDefaultObjectMapper()->getInfo().http_content_type; \ } // FOR EACH // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_DECL_FIRST(INDEX, COUNT, X) \ OATPP_MACRO_API_CONTROLLER_PARAM_TYPE X OATPP_MACRO_API_CONTROLLER_PARAM_NAME X #define OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_DECL_REST(INDEX, COUNT, X) \ , OATPP_MACRO_API_CONTROLLER_PARAM_TYPE X OATPP_MACRO_API_CONTROLLER_PARAM_NAME X #define OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_PUT(INDEX, COUNT, X) \ OATPP_MACRO_API_CONTROLLER_PARAM_MACRO X #define OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_CALL_FIRST(INDEX, COUNT, X) \ OATPP_MACRO_API_CONTROLLER_PARAM_NAME X #define OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_CALL_REST(INDEX, COUNT, X) \ , OATPP_MACRO_API_CONTROLLER_PARAM_NAME X #define OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_INFO(INDEX, COUNT, X) \ OATPP_MACRO_API_CONTROLLER_PARAM_INFO X // ENDPOINT_INFO MACRO // ------------------------------------------------------ #define ENDPOINT_INFO(NAME) \ \ std::shared_ptr<oatpp::web::server::api::Endpoint::Info> Z__ENDPOINT_CREATE_ADDITIONAL_INFO_##NAME() { \ auto info = Z__EDNPOINT_INFO_GET_INSTANCE_##NAME(); \ Z__ENDPOINT_ADD_INFO_##NAME(info); \ return info; \ } \ \ const std::shared_ptr<oatpp::web::server::api::Endpoint::Info> Z__ENDPOINT_ADDITIONAL_INFO_##NAME = Z__ENDPOINT_CREATE_ADDITIONAL_INFO_##NAME(); \ \ void Z__ENDPOINT_ADD_INFO_##NAME(const std::shared_ptr<oatpp::web::server::api::Endpoint::Info>& info) // ENDPOINT MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_DEFAULTS(NAME, METHOD, PATH) \ \ template<class T> \ static typename std::shared_ptr<Handler<T>> Z__ENDPOINT_HANDLER_GET_INSTANCE_##NAME(T* controller) { \ auto handler = std::static_pointer_cast<Handler<T>>(controller->getEndpointHandler(#NAME)); \ if(!handler) { \ handler = Handler<T>::createShared(controller, &T::Z__PROXY_METHOD_##NAME, nullptr); \ controller->setEndpointHandler(#NAME, handler); \ } \ return handler; \ } \ \ std::shared_ptr<oatpp::web::server::api::Endpoint::Info> Z__EDNPOINT_INFO_GET_INSTANCE_##NAME() { \ std::shared_ptr<oatpp::web::server::api::Endpoint::Info> info = getEndpointInfo(#NAME); \ if(!info){ \ info = oatpp::web::server::api::Endpoint::Info::createShared(); \ setEndpointInfo(#NAME, info); \ } \ return info; \ } #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_0(NAME, METHOD, PATH) \ \ EndpointInfoBuilder Z__CREATE_ENDPOINT_INFO_##NAME = [this](){ \ auto info = Z__EDNPOINT_INFO_GET_INSTANCE_##NAME(); \ info->name = #NAME; \ info->path = ((m_routerPrefix != nullptr) ? m_routerPrefix + PATH : PATH); \ info->method = METHOD; \ if (info->path == "") { \ info->path = "/"; \ } \ return info; \ }; \ \ const std::shared_ptr<oatpp::web::server::api::Endpoint> Z__ENDPOINT_##NAME = createEndpoint(m_endpoints, \ Z__ENDPOINT_HANDLER_GET_INSTANCE_##NAME(this), \ Z__CREATE_ENDPOINT_INFO_##NAME); #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_0(NAME, METHOD, PATH) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_DEFAULTS(NAME, METHOD, PATH) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_0(NAME, METHOD, PATH) \ \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> \ Z__PROXY_METHOD_##NAME(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& __request) \ { \ (void)__request; \ return NAME(); \ } \ \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> NAME() //////////////////// #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_1(NAME, METHOD, PATH, ...) \ \ EndpointInfoBuilder Z__CREATE_ENDPOINT_INFO_##NAME = [this](){ \ auto info = Z__EDNPOINT_INFO_GET_INSTANCE_##NAME(); \ info->name = #NAME; \ info->path = ((m_routerPrefix != nullptr) ? m_routerPrefix + PATH : PATH); \ info->method = METHOD; \ OATPP_MACRO_FOREACH(OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_INFO, __VA_ARGS__) \ return info; \ }; \ \ const std::shared_ptr<oatpp::web::server::api::Endpoint> Z__ENDPOINT_##NAME = createEndpoint(m_endpoints, \ Z__ENDPOINT_HANDLER_GET_INSTANCE_##NAME(this), \ Z__CREATE_ENDPOINT_INFO_##NAME); #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_1(NAME, METHOD, PATH, ...) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_DEFAULTS(NAME, METHOD, PATH) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_1(NAME, METHOD, PATH, __VA_ARGS__) \ \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> \ Z__PROXY_METHOD_##NAME(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& __request) \ { \ OATPP_MACRO_FOREACH(OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_PUT, __VA_ARGS__) \ return NAME( \ OATPP_MACRO_FOREACH_FIRST_AND_REST( \ OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_CALL_FIRST, \ OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_CALL_REST, \ __VA_ARGS__ \ ) \ ); \ } \ \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> NAME(\ OATPP_MACRO_FOREACH_FIRST_AND_REST( \ OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_DECL_FIRST, \ OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_DECL_REST, \ __VA_ARGS__ \ ) \ ) // Chooser #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_0(METHOD, PATH, NAME) \ OATPP_MACRO_EXPAND(OATPP_MACRO_API_CONTROLLER_ENDPOINT_0(NAME, METHOD, PATH)) #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_1(METHOD, PATH, NAME, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_API_CONTROLLER_ENDPOINT_1(NAME, METHOD, PATH, __VA_ARGS__)) /** * Codegen macro to be used in `oatpp::web::server::api::ApiController` to generate Endpoint. * @param METHOD - Http method ("GET", "POST", "PUT", etc.). * @param PATH - Path to endpoint (without host). * @param NAME - Name of the generated method. * @return - std::shared_ptr to &id:oatpp::web::protocol::http::outgoing::Response;. */ #define ENDPOINT(METHOD, PATH, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_, (__VA_ARGS__)) (METHOD, PATH, __VA_ARGS__)) /** * Endpoint interceptor */ #define ENDPOINT_INTERCEPTOR(ENDPOINT_NAME, NAME) \ \ Handler<oatpp::web::server::api::ApiController>::Method \ Z__INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME = Z__INTERCEPTOR_METHOD_SET_##ENDPOINT_NAME ##_ ##NAME(this); \ \ template<class T> \ Handler<oatpp::web::server::api::ApiController>::Method Z__INTERCEPTOR_METHOD_SET_##ENDPOINT_NAME ##_ ##NAME (T* controller) { \ return static_cast<Handler<oatpp::web::server::api::ApiController>::Method>( \ Z__ENDPOINT_HANDLER_GET_INSTANCE_##ENDPOINT_NAME(controller)->setMethod(&T::Z__PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME) \ ); \ } \ \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> \ Z__PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& request) { \ return Z__USER_PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME(this, request); \ } \ \ template<class T> \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> \ Z__USER_PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME( \ T*, \ const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& request \ ) { \ auto intercepted = static_cast<typename Handler<T>::Method>(Z__INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME); \ return Z__USER_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME <T> (intercepted, request); \ } \ \ template<class T> \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> \ Z__USER_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME( \ typename Handler<T>::Method intercepted, \ const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& request \ ) // ENDPOINT ASYNC MACRO // ------------------------------------------------------ /* * 1 - Method to obtain endpoint call function ptr * 2 - Endpoint info singleton */ #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL_DEFAULTS(NAME, METHOD, PATH) \ \ template<class T> \ static typename std::shared_ptr<Handler<T>> Z__ENDPOINT_HANDLER_GET_INSTANCE_##NAME(T* controller) { \ auto handler = std::static_pointer_cast<Handler<T>>(controller->getEndpointHandler(#NAME)); \ if(!handler) { \ handler = Handler<T>::createShared(controller, nullptr, &T::Z__PROXY_METHOD_##NAME); \ controller->setEndpointHandler(#NAME, handler); \ } \ return handler; \ } \ \ std::shared_ptr<oatpp::web::server::api::Endpoint::Info> Z__EDNPOINT_INFO_GET_INSTANCE_##NAME() { \ std::shared_ptr<oatpp::web::server::api::Endpoint::Info> info = getEndpointInfo(#NAME); \ if(!info){ \ info = oatpp::web::server::api::Endpoint::Info::createShared(); \ setEndpointInfo(#NAME, info); \ } \ return info; \ } /* * 1 - Endpoint info instance * 2 - Endpoint instance */ #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL(NAME, METHOD, PATH) \ \ EndpointInfoBuilder Z__CREATE_ENDPOINT_INFO_##NAME = [this](){ \ auto info = Z__EDNPOINT_INFO_GET_INSTANCE_##NAME(); \ info->name = #NAME; \ info->path = PATH; \ info->method = METHOD; \ return info; \ }; \ \ const std::shared_ptr<oatpp::web::server::api::Endpoint> Z__ENDPOINT_##NAME = createEndpoint(m_endpoints, \ Z__ENDPOINT_HANDLER_GET_INSTANCE_##NAME(this), \ Z__CREATE_ENDPOINT_INFO_##NAME); /** * Codegen macro to be used in `oatpp::web::server::api::ApiController` to generate Asynchronous Endpoint. * @param METHOD - Http method ("GET", "POST", "PUT", etc.). * @param PATH - Path to endpoint (without host). * @param NAME - Name of the generated method. * @return - &id:oatpp::async::Action;. */ #define ENDPOINT_ASYNC(METHOD, PATH, NAME) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL_DEFAULTS(NAME, METHOD, PATH) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL(NAME, METHOD, PATH) \ \ oatpp::async::CoroutineStarterForResult<const std::shared_ptr<oatpp::web::protocol::http::outgoing::Response>&> \ Z__PROXY_METHOD_##NAME(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& __request) \ { \ return NAME::startForResult(this, __request); \ } \ \ class NAME : public HandlerCoroutine<NAME, __ControllerType> /** * Auxiliary codegen macro for `ENDPOINT_ASYNC` to generate correct constructor for Asynchronous Endpoint Coroutine. * @NAME - Name of the endpoint. Exact the same name as was passed to `ENDPOINT_ASYNC` macro. */ #define ENDPOINT_ASYNC_INIT(NAME) \ public: \ \ NAME(__ControllerType* pController, \ const std::shared_ptr<IncomingRequest>& pRequest) \ : HandlerCoroutine(pController, pRequest) \ {} /** * Endpoint interceptor */ #define ENDPOINT_INTERCEPTOR_ASYNC(ENDPOINT_NAME, NAME) \ \ Handler<oatpp::web::server::api::ApiController>::MethodAsync \ Z__INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME = Z__INTERCEPTOR_METHOD_SET_##ENDPOINT_NAME ##_ ##NAME(this); \ \ template<class T> \ Handler<oatpp::web::server::api::ApiController>::MethodAsync Z__INTERCEPTOR_METHOD_SET_##ENDPOINT_NAME ##_ ##NAME (T* controller) { \ return static_cast<Handler<oatpp::web::server::api::ApiController>::MethodAsync>( \ Z__ENDPOINT_HANDLER_GET_INSTANCE_##ENDPOINT_NAME(controller)->setMethodAsync(&T::Z__PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME) \ ); \ } \ \ oatpp::async::CoroutineStarterForResult<const std::shared_ptr<oatpp::web::protocol::http::outgoing::Response>&> \ Z__PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& request) { \ return Z__USER_PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME(this, request); \ } \ \ template<class T> \ oatpp::async::CoroutineStarterForResult<const std::shared_ptr<oatpp::web::protocol::http::outgoing::Response>&> \ Z__USER_PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME( \ T*, \ const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& request \ ) { \ auto intercepted = static_cast<typename Handler<T>::MethodAsync>(Z__INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME); \ return Z__USER_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME <T> (intercepted, request); \ } \ \ template<class T> \ oatpp::async::CoroutineStarterForResult<const std::shared_ptr<oatpp::web::protocol::http::outgoing::Response>&> \ Z__USER_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME( \ typename Handler<T>::MethodAsync intercepted, \ const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& request \ )
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/base_define.hpp
C++
apache-2.0
27,070
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #undef OATPP_MACRO_API_CONTROLLER_PARAM_MACRO #undef OATPP_MACRO_API_CONTROLLER_PARAM_INFO #undef OATPP_MACRO_API_CONTROLLER_PARAM_TYPE #undef OATPP_MACRO_API_CONTROLLER_PARAM_NAME #undef OATPP_MACRO_API_CONTROLLER_PARAM_TYPE_STR #undef OATPP_MACRO_API_CONTROLLER_PARAM_NAME_STR #undef OATPP_MACRO_API_CONTROLLER_PARAM #undef REQUEST #undef HEADER #undef PATH #undef QUERIES #undef QUERY #undef BODY_STRING #undef BODY_DTO // INIT // ------------------------------------------------------ #undef REST_CONTROLLER_INIT #undef OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR // REQUEST MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_REQUEST #undef OATPP_MACRO_API_CONTROLLER_REQUEST_INFO // HEADER MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_HEADER_1 #undef OATPP_MACRO_API_CONTROLLER_HEADER_2 #undef OATPP_MACRO_API_CONTROLLER_HEADER // __INFO #undef OATPP_MACRO_API_CONTROLLER_HEADER_INFO_1 #undef OATPP_MACRO_API_CONTROLLER_HEADER_INFO_2 #undef OATPP_MACRO_API_CONTROLLER_HEADER_INFO // PATH MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_PATH_1 #undef OATPP_MACRO_API_CONTROLLER_PATH_2 #undef OATPP_MACRO_API_CONTROLLER_PATH // __INFO #undef OATPP_MACRO_API_CONTROLLER_PATH_INFO_1 #undef OATPP_MACRO_API_CONTROLLER_PATH_INFO_2 #undef OATPP_MACRO_API_CONTROLLER_PATH_INFO // QUERIES MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_QUERIES #undef OATPP_MACRO_API_CONTROLLER_QUERIES_INFO // QUERY MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_QUERY_1 #undef OATPP_MACRO_API_CONTROLLER_QUERY_2 #undef OATPP_MACRO_API_CONTROLLER_QUERY // __INFO #undef OATPP_MACRO_API_CONTROLLER_QUERY_INFO_1 #undef OATPP_MACRO_API_CONTROLLER_QUERY_INFO_2 #undef OATPP_MACRO_API_CONTROLLER_QUERY_INFO // BODY_STRING MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_BODY_STRING // __INFO #undef OATPP_MACRO_API_CONTROLLER_BODY_STRING_INFO // BODY_DTO MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_BODY_DTO // __INFO #undef OATPP_MACRO_API_CONTROLLER_BODY_DTO_INFO // FOR EACH // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_DECL #undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_PUT #undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_CALL #undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_INFO // ENDPOINT_INFO MACRO // ------------------------------------------------------ #undef ENDPOINT_INFO // ENDPOINT MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_DEFAULTS #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_0 #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_0 #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_1 #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_1 #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_0 #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_1 #undef ENDPOINT #undef ENDPOINT_INTERCEPTOR // ENDPOINT ASYNC MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL_DEFAULTS #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL #undef ENDPOINT_ASYNC #undef ENDPOINT_ASYNC_INIT #undef ENDPOINT_INTERCEPTOR_ASYNC
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/base_undef.hpp
C++
apache-2.0
4,471
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #define BUNDLE(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_BUNDLE, OATPP_MACRO_API_CONTROLLER_BUNDLE_INFO, TYPE, (__VA_ARGS__)) // BUNDLE MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_BUNDLE_1(TYPE, NAME) \ TYPE NAME = __request->getBundleData<TYPE>(#NAME); #define OATPP_MACRO_API_CONTROLLER_BUNDLE_2(TYPE, NAME, QUALIFIER) \ TYPE NAME = __request->getBundleData<TYPE>(QUALIFIER); #define OATPP_MACRO_API_CONTROLLER_BUNDLE(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_BUNDLE_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) #define OATPP_MACRO_API_CONTROLLER_BUNDLE_INFO(TYPE, PARAM_LIST)
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/bundle_define.hpp
C++
apache-2.0
1,787
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #undef BUNDLE #undef OATPP_MACRO_API_CONTROLLER_BUNDLE_1 #undef OATPP_MACRO_API_CONTROLLER_BUNDLE_2 #undef OATPP_MACRO_API_CONTROLLER_BUNDLE #undef OATPP_MACRO_API_CONTROLLER_BUNDLE_INFO
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/bundle_undef.hpp
C++
apache-2.0
1,257
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #define OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_ORIGIN "*" #define OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_METHODS "GET, POST, OPTIONS" #define OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_HEADERS "DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range, Authorization" #define OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_MAX_AGE "1728000" #define OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY(ARG_ORIGIN, ARG_METHODS, ARG_HEADERS, ARG_MAX_AGE) \ resp->putHeaderIfNotExists(oatpp::web::protocol::http::Header::CORS_ORIGIN, ARG_ORIGIN); \ resp->putHeaderIfNotExists(oatpp::web::protocol::http::Header::CORS_METHODS, ARG_METHODS); \ resp->putHeaderIfNotExists(oatpp::web::protocol::http::Header::CORS_HEADERS, ARG_HEADERS);\ resp->putHeaderIfNotExists(oatpp::web::protocol::http::Header::CORS_MAX_AGE, ARG_MAX_AGE); #define OATPP_MACRO_API_CONTROLLER_ADD_CORS_OPTIONS_DECL(ENDPOINTNAME) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_DEFAULTS(Z__CORS_OPTIONS_DECL_##ENDPOINTNAME, "OPTIONS", "") \ EndpointInfoBuilder Z__CREATE_ENDPOINT_INFO_Z__CORS_OPTIONS_DECL_##ENDPOINTNAME = [this](){ \ auto info = Z__EDNPOINT_INFO_GET_INSTANCE_Z__CORS_OPTIONS_DECL_##ENDPOINTNAME(); \ info->name = "CORS_OPTIONS_DECL_" #ENDPOINTNAME; \ info->path = Z__ENDPOINT_##ENDPOINTNAME->info()->path; \ info->method = "OPTIONS"; \ info->pathParams = Z__ENDPOINT_##ENDPOINTNAME->info()->pathParams; \ info->hide = true; \ return info; \ }; \ \ const std::shared_ptr<oatpp::web::server::api::Endpoint> \ Z__ENDPOINT_Z__CORS_OPTIONS_DECL_##ENDPOINTNAME = createEndpoint(m_endpoints, \ Z__ENDPOINT_HANDLER_GET_INSTANCE_Z__CORS_OPTIONS_DECL_##ENDPOINTNAME(this), \ Z__CREATE_ENDPOINT_INFO_Z__CORS_OPTIONS_DECL_##ENDPOINTNAME);\ \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> \ Z__PROXY_METHOD_Z__CORS_OPTIONS_DECL_##ENDPOINTNAME(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& __request) \ { \ (void)__request; \ return Z__CORS_OPTIONS_DECL_##ENDPOINTNAME(); \ } \ \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> Z__CORS_OPTIONS_DECL_##ENDPOINTNAME() #define OATPP_MACRO_API_CONTROLLER_ADD_CORS_MACRO_1(ENDPOINTNAME, ...) \ ENDPOINT_INTERCEPTOR(ENDPOINTNAME, CORS) { \ auto resp = (this->*intercepted)(request); \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY( \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_ORIGIN, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_METHODS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_HEADERS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_MAX_AGE \ ) \ return resp; \ } \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_OPTIONS_DECL(ENDPOINTNAME) { \ auto resp = createResponse(Status::CODE_204, ""); \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY( \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_ORIGIN, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_METHODS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_HEADERS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_MAX_AGE \ ) \ return resp; \ } #define OATPP_MACRO_API_CONTROLLER_ADD_CORS_MACRO_2(ENDPOINTNAME, ORIGIN) \ ENDPOINT_INTERCEPTOR(ENDPOINTNAME, CORS) { \ auto resp = (this->*intercepted)(request); \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY( \ ORIGIN, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_METHODS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_HEADERS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_MAX_AGE \ ) \ return resp; \ } \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_OPTIONS_DECL(ENDPOINTNAME) { \ auto resp = createResponse(Status::CODE_204, ""); \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY( \ ORIGIN, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_METHODS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_HEADERS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_MAX_AGE \ ) \ return resp; \ } #define OATPP_MACRO_API_CONTROLLER_ADD_CORS_MACRO_3(ENDPOINTNAME, ORIGIN, METHODS) \ ENDPOINT_INTERCEPTOR(ENDPOINTNAME, CORS) { \ auto resp = (this->*intercepted)(request); \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY( \ ORIGIN, \ METHODS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_HEADERS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_MAX_AGE \ ) \ return resp; \ } \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_OPTIONS_DECL(ENDPOINTNAME) { \ auto resp = createResponse(Status::CODE_204, ""); \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY( \ ORIGIN, \ METHODS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_HEADERS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_MAX_AGE \ ) \ return resp; \ } #define OATPP_MACRO_API_CONTROLLER_ADD_CORS_MACRO_4(ENDPOINTNAME, ORIGIN, METHODS, HEADERS) \ ENDPOINT_INTERCEPTOR(ENDPOINTNAME, CORS) { \ auto resp = (this->*intercepted)(request); \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY( \ ORIGIN, \ METHODS, \ HEADERS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_MAX_AGE \ ) \ return resp; \ } \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_OPTIONS_DECL(ENDPOINTNAME) { \ auto resp = createResponse(Status::CODE_204, ""); \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY( \ ORIGIN, \ METHODS, \ HEADERS, \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_MAX_AGE \ ) \ return resp; \ } #define OATPP_MACRO_API_CONTROLLER_ADD_CORS_MACRO_5(ENDPOINTNAME, ORIGIN, METHODS, HEADERS, MAX_AGE) \ ENDPOINT_INTERCEPTOR(ENDPOINTNAME, CORS) { \ auto resp = (this->*intercepted)(request); \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY(ORIGIN, METHODS, HEADERS, MAX_AGE) \ return resp; \ } \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_OPTIONS_DECL(ENDPOINTNAME) { \ auto resp = createResponse(Status::CODE_204, ""); \ OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY(ORIGIN, METHODS, HEADERS, MAX_AGE) \ return resp; \ } #define ADD_CORS(...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_ADD_CORS_MACRO_, (__VA_ARGS__)) (__VA_ARGS__))
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/cors_define.hpp
C++
apache-2.0
7,141
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #undef ADD_CORS #undef OATPP_MACRO_API_CONTROLLER_ADD_CORS_MACRO_1 #undef OATPP_MACRO_API_CONTROLLER_ADD_CORS_MACRO_2 #undef OATPP_MACRO_API_CONTROLLER_ADD_CORS_MACRO_3 #undef OATPP_MACRO_API_CONTROLLER_ADD_CORS_MACRO_4 #undef OATPP_MACRO_API_CONTROLLER_ADD_CORS_MACRO_5 #undef OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY #undef OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_ORIGIN #undef OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_METHODS #undef OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_HEADERS #undef OATPP_MACRO_API_CONTROLLER_ADD_CORS_BODY_DEFAULT_MAX_AGE
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/cors_undef.hpp
C++
apache-2.0
1,643
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ // Defaults /** * Codegen macro to be used in classes extending &id:oatpp::data::mapping::type::Object; to generate required fields/methods/constructors for DTO object. * @param TYPE_NAME - name of the DTO class. * @param TYPE_EXTEND - name of the parent DTO class. If DTO extends &id:oatpp::data::mapping::type::Object; TYPE_EXETENDS should be `Object`. */ #define DTO_INIT(TYPE_NAME, TYPE_EXTEND) \ template<class __Z__T__PARAM> \ friend class oatpp::data::mapping::type::__class::Object; \ public: \ typedef TYPE_NAME Z__CLASS; \ typedef TYPE_EXTEND Z__CLASS_EXTENDED; \ typedef oatpp::data::mapping::type::DTOWrapper<Z__CLASS> Wrapper; \ private: \ \ static const oatpp::Type* getParentType() { \ return oatpp::Object<Z__CLASS_EXTENDED>::Class::getType(); \ } \ \ static const char* Z__CLASS_TYPE_NAME() { \ return #TYPE_NAME; \ } \ \ static oatpp::data::mapping::type::BaseObject::Properties* Z__CLASS_GET_FIELDS_MAP(){ \ static oatpp::data::mapping::type::BaseObject::Properties map = oatpp::data::mapping::type::BaseObject::Properties(); \ return &map; \ } \ \ public: \ \ template<typename ... Args> \ static Wrapper createShared(Args... args){ \ return Wrapper(std::make_shared<Z__CLASS>(args...), Wrapper::Class::getType()); \ } // Fields #define OATPP_MACRO_DTO_FIELD_1(TYPE, NAME) \ \ static v_int64 Z__PROPERTY_OFFSET_##NAME() { \ char buffer[sizeof(Z__CLASS)]; \ auto obj = static_cast<Z__CLASS*>((void*)buffer); \ auto ptr = &obj->NAME; \ return (v_int64) ptr - (v_int64) buffer; \ } \ \ static oatpp::data::mapping::type::BaseObject::Property* Z__PROPERTY_SINGLETON_##NAME() { \ static oatpp::data::mapping::type::BaseObject::Property* property = \ new oatpp::data::mapping::type::BaseObject::Property(Z__PROPERTY_OFFSET_##NAME(), \ #NAME, \ TYPE::Class::getType()); \ return property; \ } \ \ static bool Z__PROPERTY_INIT_##NAME(... /* default initializer for all cases */) { \ Z__CLASS_GET_FIELDS_MAP()->pushBack(Z__PROPERTY_SINGLETON_##NAME()); \ return true; \ } \ \ static TYPE Z__PROPERTY_INITIALIZER_PROXY_##NAME() { \ static bool initialized = Z__PROPERTY_INIT_##NAME(1 /* init info if found */, \ 1 /* init type selector if found */); \ (void)initialized; \ return TYPE(); \ } \ \ TYPE NAME = Z__PROPERTY_INITIALIZER_PROXY_##NAME() #define OATPP_MACRO_DTO_FIELD_2(TYPE, NAME, QUALIFIER) \ \ static v_int64 Z__PROPERTY_OFFSET_##NAME() { \ char buffer[sizeof(Z__CLASS)]; \ auto obj = static_cast<Z__CLASS*>((void*)buffer); \ auto ptr = &obj->NAME; \ return (v_int64) ptr - (v_int64) buffer; \ } \ \ static oatpp::data::mapping::type::BaseObject::Property* Z__PROPERTY_SINGLETON_##NAME() { \ static oatpp::data::mapping::type::BaseObject::Property* property = \ new oatpp::data::mapping::type::BaseObject::Property(Z__PROPERTY_OFFSET_##NAME(), \ QUALIFIER, \ TYPE::Class::getType()); \ return property; \ } \ \ static bool Z__PROPERTY_INIT_##NAME(... /* default initializer for all cases */) { \ Z__CLASS_GET_FIELDS_MAP()->pushBack(Z__PROPERTY_SINGLETON_##NAME()); \ return true; \ } \ \ static TYPE Z__PROPERTY_INITIALIZER_PROXY_##NAME() { \ static bool initialized = Z__PROPERTY_INIT_##NAME(1 /* init info if found */, \ 1 /* init type selector if found */); \ (void)initialized; \ return TYPE(); \ } \ \ TYPE NAME = Z__PROPERTY_INITIALIZER_PROXY_##NAME() /** * Codegen macro to generate fields of DTO object. * @param TYPE - type of the field. * @param NAME - name of the field. * @param QUALIFIER_NAME - additional (optional) field to specify serialized name of the field. If not specified it will be same as NAME. */ #define DTO_FIELD(TYPE, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_SELECTOR(OATPP_MACRO_DTO_FIELD_, (__VA_ARGS__)) (TYPE, __VA_ARGS__)) // DTO_FIELD_INFO #define DTO_FIELD_INFO(NAME) \ \ static bool Z__PROPERTY_INIT_##NAME(int, ...) { \ Z__PROPERTY_INIT_##NAME(); /* call first initialization */ \ Z__PROPERTY_ADD_INFO_##NAME(&Z__PROPERTY_SINGLETON_##NAME()->info); \ return true; \ } \ \ static void Z__PROPERTY_ADD_INFO_##NAME(oatpp::data::mapping::type::BaseObject::Property::Info* info) #define DTO_FIELD_TYPE_SELECTOR(NAME) \ \ class Z__PROPERTY_TYPE_SELECTOR_##NAME : public oatpp::BaseObject::Property::FieldTypeSelector<Z__CLASS> { \ public: \ const oatpp::Type* selectFieldType(Z__CLASS* self) override { \ return self->Z__PROPERTY_TYPE_SELECTOR_METHOD_##NAME(); \ } \ }; \ \ static bool Z__PROPERTY_INIT_##NAME(int, int) { \ Z__PROPERTY_INIT_##NAME(1); /* call property info initialization */ \ Z__PROPERTY_SINGLETON_##NAME()->info.typeSelector = new Z__PROPERTY_TYPE_SELECTOR_##NAME(); \ return true; \ } \ \ const oatpp::Type* Z__PROPERTY_TYPE_SELECTOR_METHOD_##NAME() // FOR EACH #define OATPP_MACRO_DTO_HC_EQ_PARAM_HC(INDEX, COUNT, X) \ result = ((result << 5) - result) + std::hash<decltype(X)>{}(X); #define OATPP_MACRO_DTO_HC_EQ_PARAM_EQ(INDEX, COUNT, X) \ && X == other.X #define DTO_HASHCODE_AND_EQUALS(...) \ v_uint64 defaultHashCode() const override { \ return 1; \ } \ \ bool defaultEquals(const DTO&) const override { \ return true; \ } \ \ v_uint64 hashCode() const { \ v_uint64 result = 1; \ result = ((result << 5) - result) + static_cast<const Z__CLASS_EXTENDED&>(*this).hashCode(); \ OATPP_MACRO_FOREACH(OATPP_MACRO_DTO_HC_EQ_PARAM_HC, __VA_ARGS__) \ return result; \ } \ \ bool operator==(const Z__CLASS& other) const { \ return static_cast<const Z__CLASS_EXTENDED&>(*this) == static_cast<const Z__CLASS_EXTENDED&>(other) \ OATPP_MACRO_FOREACH(OATPP_MACRO_DTO_HC_EQ_PARAM_EQ, __VA_ARGS__) \ ; \ } \ \ bool operator!=(const Z__CLASS& other) const { \ return !this->operator==(other); \ } /** * Hashcode and Equals macro. <br> * List DTO-fields which should count in hashcode and equals operators. */ #define DTO_HC_EQ(...) DTO_HASHCODE_AND_EQUALS(__VA_ARGS__)
vincent-in-black-sesame/oat
src/oatpp/codegen/dto/base_define.hpp
C++
apache-2.0
7,307
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #undef DTO_INIT // Fields #undef OATPP_MACRO_DTO_FIELD_1 #undef OATPP_MACRO_DTO_FIELD_2 #undef DTO_FIELD // Fields Info #undef DTO_FIELD_INFO // Type Selector #undef DTO_FIELD_TYPE_SELECTOR // Hashcode & Equals #undef OATPP_MACRO_DTO_HC_EQ_PARAM_HC #undef OATPP_MACRO_DTO_HC_EQ_PARAM_EQ #undef DTO_HASHCODE_AND_EQUALS #undef DTO_HC_EQ
vincent-in-black-sesame/oat
src/oatpp/codegen/dto/base_undef.hpp
C++
apache-2.0
1,412
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #define OATPP_MACRO_DTO_ENUM_PARAM_MACRO(MACRO, NAME, PARAM_LIST) MACRO(NAME, PARAM_LIST) #define OATPP_MACRO_DTO_ENUM_PARAM_NAME(MACRO, NAME, PARAM_LIST) NAME #define OATPP_MACRO_DTO_ENUM_PARAM_NAME_STR(MACRO, NAME, PARAM_LIST) #NAME #define OATPP_MACRO_DTO_ENUM_PARAM_VALUE(MACRO, NAME, PARAM_LIST) OATPP_MACRO_FIRSTARG PARAM_LIST #define OATPP_MACRO_DTO_ENUM_PARAM_VALUE_STR(MACRO, NAME, PARAM_LIST) OATPP_MACRO_FIRSTARG_STR PARAM_LIST #define OATPP_MACRO_DTO_ENUM_PARAM(MACRO, NAME, PARAM_LIST) (MACRO, NAME, PARAM_LIST) /** * Enum entry value. * @param NAME - name of the enum. **required**. * @param ORDINAL_VALUE - corresponding ordinal value. **required**. * @param QUALIFIER - name qualifier to be used instead of the `NAME`. **optional**. * @param DESCRIPTION - description of the enum value. **optional**. */ #define VALUE(NAME, ...) \ OATPP_MACRO_DTO_ENUM_PARAM(OATPP_MACRO_DTO_ENUM_VALUE, NAME, (__VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// #define OATPP_MACRO_DTO_ENUM_MACRO_SELECTOR(MACRO, NAME, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_SELECTOR(MACRO, (__VA_ARGS__)) (NAME, __VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// // VALUE MACRO #define OATPP_MACRO_DTO_ENUM_VALUE_1(NAME, VAL) \ { \ oatpp::data::mapping::type::EnumValueInfo<EnumType> entry = {EnumType::NAME, index ++, #NAME, nullptr}; \ info.byName.insert({#NAME, entry}); \ info.byValue.insert({static_cast<v_uint64>(EnumType::NAME), entry}); \ info.byIndex.push_back(entry); \ } #define OATPP_MACRO_DTO_ENUM_VALUE_2(NAME, VAL, QUALIFIER) \ { \ oatpp::data::mapping::type::EnumValueInfo<EnumType> entry = {EnumType::NAME, index ++, QUALIFIER, nullptr}; \ info.byName.insert({QUALIFIER, entry}); \ info.byValue.insert({static_cast<v_uint64>(EnumType::NAME), entry}); \ info.byIndex.push_back(entry); \ } #define OATPP_MACRO_DTO_ENUM_VALUE_3(NAME, VAL, QUALIFIER, DESCRIPTION) \ { \ oatpp::data::mapping::type::EnumValueInfo<EnumType> entry = {EnumType::NAME, index ++, QUALIFIER, DESCRIPTION}; \ info.byName.insert({QUALIFIER, entry}); \ info.byValue.insert({static_cast<v_uint64>(EnumType::NAME), entry}); \ info.byIndex.push_back(entry); \ } #define OATPP_MACRO_DTO_ENUM_VALUE(NAME, PARAM_LIST) \ OATPP_MACRO_DTO_ENUM_MACRO_SELECTOR(OATPP_MACRO_DTO_ENUM_VALUE_, NAME, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // FOR EACH #define OATPP_MACRO_DTO_ENUM_PARAM_DECL_FIRST(INDEX, COUNT, X) \ OATPP_MACRO_DTO_ENUM_PARAM_NAME X = OATPP_MACRO_DTO_ENUM_PARAM_VALUE X #define OATPP_MACRO_DTO_ENUM_PARAM_DECL_REST(INDEX, COUNT, X) \ , OATPP_MACRO_DTO_ENUM_PARAM_NAME X = OATPP_MACRO_DTO_ENUM_PARAM_VALUE X #define OATPP_MACRO_DTO_ENUM_PARAM_PUT(INDEX, COUNT, X) \ OATPP_MACRO_DTO_ENUM_PARAM_MACRO X // ENUM MACRO #define OATPP_ENUM_0(NAME, ORDINAL_TYPE) \ enum class NAME : ORDINAL_TYPE {}; \ \ namespace { \ \ class Z__OATPP_ENUM_META_##NAME : public oatpp::data::mapping::type::EnumMeta<NAME> { \ private: \ \ static bool init() { \ auto& info = *EnumMeta<NAME>::getInfo(); \ v_int32 index = 0; \ (void)index; \ info.nameQualifier = #NAME; \ return true; \ } \ \ public: \ \ static bool initializer() { \ static bool initialized = init(); \ return initialized; \ } \ \ }; \ \ bool Z__OATPP_ENUM_META_INITIALIZER_##NAME = Z__OATPP_ENUM_META_##NAME::initializer(); \ \ } #define OATPP_ENUM_1(NAME, ORDINAL_TYPE, ...) \ enum class NAME : ORDINAL_TYPE { \ OATPP_MACRO_FOREACH_FIRST_AND_REST( \ OATPP_MACRO_DTO_ENUM_PARAM_DECL_FIRST, \ OATPP_MACRO_DTO_ENUM_PARAM_DECL_REST, \ __VA_ARGS__ \ ) \ }; \ \ class Z__OATPP_ENUM_META_##NAME : public oatpp::data::mapping::type::EnumMeta<NAME> { \ private: \ \ static bool init() { \ auto& info = *EnumMeta<NAME>::getInfo(); \ v_int32 index = 0; \ info.nameQualifier = #NAME; \ OATPP_MACRO_FOREACH(OATPP_MACRO_DTO_ENUM_PARAM_PUT, __VA_ARGS__) \ return true; \ } \ \ public: \ \ static bool initializer() { \ static bool initialized = init(); \ return initialized; \ } \ \ }; \ \ static bool Z__OATPP_ENUM_META_INITIALIZER_##NAME = Z__OATPP_ENUM_META_##NAME::initializer(); // Chooser #define OATPP_ENUM_MACRO_0(NAME, ORDINAL_TYPE) \ OATPP_ENUM_0(NAME, ORDINAL_TYPE) #define OATPP_ENUM_MACRO_1(NAME, ORDINAL_TYPE, ...) \ OATPP_ENUM_1(NAME, ORDINAL_TYPE, __VA_ARGS__) /** * Codegen macro to generate oatpp mapping-enabled enum. * @param NAME - name of the enum. **required**. * @param UNDERLYING_TYPE - underlying ordinal type. **required**. * @param ... - enum values defined with &l:VALUE (...);. macro. */ #define ENUM(NAME, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_ENUM_MACRO_, (__VA_ARGS__)) (NAME, __VA_ARGS__))
vincent-in-black-sesame/oat
src/oatpp/codegen/dto/enum_define.hpp
C++
apache-2.0
5,843
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #undef OATPP_MACRO_DTO_ENUM_PARAM_MACRO #undef OATPP_MACRO_DTO_ENUM_PARAM_NAME #undef OATPP_MACRO_DTO_ENUM_PARAM_NAME_STR #undef OATPP_MACRO_DTO_ENUM_PARAM_VALUE #undef OATPP_MACRO_DTO_ENUM_PARAM_VALUE_STR #undef OATPP_MACRO_DTO_ENUM_PARAM #undef VALUE ////////////////////////////////////////////////////////////////////////// #undef OATPP_MACRO_DTO_ENUM_MACRO_SELECTOR ////////////////////////////////////////////////////////////////////////// // VALUE MACRO #undef OATPP_MACRO_DTO_ENUM_VALUE_1 #undef OATPP_MACRO_DTO_ENUM_VALUE_2 #undef OATPP_MACRO_DTO_ENUM_VALUE_3 #undef OATPP_MACRO_DTO_ENUM_VALUE // FOR EACH #undef OATPP_MACRO_DTO_ENUM_PARAM_DECL_FIRST #undef OATPP_MACRO_DTO_ENUM_PARAM_DECL_REST #undef OATPP_MACRO_DTO_ENUM_PARAM_PUT // ENUM MACRO #undef OATPP_ENUM_0 #undef OATPP_ENUM_1 // Chooser #undef OATPP_ENUM_MACRO_0 #undef OATPP_ENUM_MACRO_1 #undef ENUM
vincent-in-black-sesame/oat
src/oatpp/codegen/dto/enum_undef.hpp
C++
apache-2.0
1,960
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "IODefinitions.hpp" #if defined(WIN32) || defined(_WIN32) #include <WinSock2.h> #endif namespace oatpp { bool isValidIOHandle(v_io_handle handle) { #if defined(WIN32) || defined(_WIN32) return handle != INVALID_SOCKET; #else return handle >= 0; #endif } }
vincent-in-black-sesame/oat
src/oatpp/core/IODefinitions.cpp
C++
apache-2.0
1,273
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_IODefinitions_hpp #define oatpp_IODefinitions_hpp #include "oatpp/core/async/Error.hpp" #include "oatpp/core/Types.hpp" namespace oatpp { /** * Represents I/O handle (ex.: file descriptor). */ #if defined(WIN32) || defined(_WIN32) #if defined(_WIN64) typedef unsigned long long v_io_handle; #else typedef unsigned long v_io_handle; #endif constexpr const v_io_handle INVALID_IO_HANDLE = v_io_handle (-1); #else typedef int v_io_handle; constexpr const v_io_handle INVALID_IO_HANDLE = v_io_handle (-1); #endif /** * Check if IO handle is valid. * @param handle - IO handle. * @return - `true` if valid. */ bool isValidIOHandle(v_io_handle handle); /** * All I/O buffer operations (like read/write(buffer, size)) should return v_io_size. <br> * * Possible return values: * <ul> * <li>**On Success** - [1..max_int64].</li> * <li>**On Error** - IOError values.</li> * </ul> * * All other values are considered to be a fatal error. * application should be terminated. */ typedef v_int64 v_io_size; /** * Final set of possible I/O operation error values. * I/O operation should not return any other error values. */ enum IOError : v_io_size { /** * In oatpp 0 is considered to be an Error as for I/O operation size. <br> * * As for argument value 0 should be handled separately of the main flow.<br> * * As for return value 0 should not be returned.<br> * I/O method should return an error describing a reason why I/O is empty instead of a zero itself.<br> * if zero is returned, client should treat it like a bad api implementation and as an error in the flow.<br> */ ZERO_VALUE = 0, /** * I/O operation is not possible any more. * Client should give up trying and free all related resources. */ BROKEN_PIPE = -1001, /** * I/O operation was interrupted because of some reason. * Client may retry read immediately. */ RETRY_READ = -1002, /** * I/O operation was interrupted because of some reason. * Client may retry immediately. */ RETRY_WRITE = -1003, }; /** * Asynchronous I/O error. <br> * Extends &id:oatpp::async::Error;. */ class AsyncIOError : public oatpp::async::Error { private: v_io_size m_code; public: /** * Constructor. * @param what - description of error type. * @param code - I/O opersation error code. &l:IOError;. */ AsyncIOError(const char* what, v_io_size code) : oatpp::async::Error(what) , m_code(code) {} /** * Constructor. * @param code - I/O opersation error code. &l:IOError;. */ AsyncIOError(v_io_size code) : oatpp::async::Error("AsyncIOError") , m_code(code) {} /** * Get I/O opersation error code. * @return - I/O opersation error code. &l:IOError;. */ v_io_size getCode() const { return m_code; } }; } #endif // oatpp_IODefinitions_hpp
vincent-in-black-sesame/oat
src/oatpp/core/IODefinitions.hpp
C++
apache-2.0
3,877
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_Types_hpp #define oatpp_Types_hpp #include "oatpp/core/data/mapping/type/Object.hpp" namespace oatpp { /** * &id:oatpp::data::mapping::type::Type;. */ typedef oatpp::data::mapping::type::Type Type; /** * &id:oatpp::data::mapping::type::ClassId;. */ typedef oatpp::data::mapping::type::ClassId ClassId; /** * ObjectWrapper. */ template <class T, class Clazz = oatpp::data::mapping::type::__class::Void> using ObjectWrapper = oatpp::data::mapping::type::ObjectWrapper<T, Clazz>; /** * ObjectWrapper over the `void*`. */ typedef oatpp::data::mapping::type::Void Void; /** * `Any` - container for mapping-enabled types. * &id:oatpp::data::mapping::type::Any; */ typedef oatpp::data::mapping::type::Any Any; /** * Mapping-Enabled String type. &id:oatpp::data::mapping::type::String; <br> * For `oatpp::String` methods see `std::string` */ typedef oatpp::data::mapping::type::String String; /** * Mapping-Enabled 8-bits int. Can hold nullptr value. &id:oatpp::data::mapping::type::Int8; */ typedef oatpp::data::mapping::type::Int8 Int8; /** * Mapping-Enabled 8-bits unsigned int. Can hold nullptr value. &id:oatpp::data::mapping::type::UInt8; */ typedef oatpp::data::mapping::type::UInt8 UInt8; /** * Mapping-Enabled 16-bits int. Can hold nullptr value. &id:oatpp::data::mapping::type::Int16; */ typedef oatpp::data::mapping::type::Int16 Int16; /** * Mapping-Enabled 16-bits unsigned int. Can hold nullptr value. &id:oatpp::data::mapping::type::UInt16; */ typedef oatpp::data::mapping::type::UInt16 UInt16; /** * Mapping-Enabled 32-bits int. Can hold nullptr value. &id:oatpp::data::mapping::type::Int32; */ typedef oatpp::data::mapping::type::Int32 Int32; /** * Mapping-Enabled 32-bits unsigned int. Can hold nullptr value. &id:oatpp::data::mapping::type::UInt32; */ typedef oatpp::data::mapping::type::UInt32 UInt32; /** * Mapping-Enabled 64-bits int. Can hold nullptr value. &id:oatpp::data::mapping::type::Int64; */ typedef oatpp::data::mapping::type::Int64 Int64; /** * Mapping-Enabled 64-bits unsigned int. Can hold nullptr value. &id:oatpp::data::mapping::type::UInt64; */ typedef oatpp::data::mapping::type::UInt64 UInt64; /** * Mapping-Enabled 32-bits float. Can hold nullptr value. &id:oatpp::data::mapping::type::Float32; */ typedef oatpp::data::mapping::type::Float32 Float32; /** * Mapping-Enabled 64-bits float (double). Can hold nullptr value. &id:oatpp::data::mapping::type::Float64; */ typedef oatpp::data::mapping::type::Float64 Float64; /** * Mapping-Enabled Boolean. Can hold nullptr value. &id:oatpp::data::mapping::type::Boolean; */ typedef oatpp::data::mapping::type::Boolean Boolean; /** * Base class for all Object-like Mapping-enabled structures. &id:oatpp::data::mapping::type::BaseObject; */ typedef oatpp::data::mapping::type::BaseObject BaseObject; /** * Base class for all DTO objects. &id:oatpp::data::mapping::type::DTO; */ typedef oatpp::data::mapping::type::DTO DTO; /** * Mapping-Enabled DTO Object. &id:oatpp::data::mapping::type::DTOWrapper; */ template <class T> using Object = oatpp::data::mapping::type::DTOWrapper<T>; /** * Mapping-Enabled Enum. &id:oatpp::data::mapping::type::Enum; */ template <class T> using Enum = oatpp::data::mapping::type::Enum<T>; /** * Mapping-Enabled Vector. &id:oatpp::data::mapping::type::Vector; */ template <class T> using Vector = oatpp::data::mapping::type::Vector<T>; /** * Abstract Vector. */ typedef oatpp::data::mapping::type::AbstractVector AbstractVector; /** * Mapping-Enabled List. &id:oatpp::data::mapping::type::List; */ template <class T> using List = oatpp::data::mapping::type::List<T>; /** * Abstract List. */ typedef oatpp::data::mapping::type::AbstractList AbstractList; /** * Mapping-Enabled UnorderedSet. &id:oatpp::data::mapping::type::UnorderedSet; */ template <class T> using UnorderedSet = oatpp::data::mapping::type::UnorderedSet<T>; /** * Abstract UnorderedSet. */ typedef oatpp::data::mapping::type::AbstractUnorderedSet AbstractUnorderedSet; /** * Mapping-Enabled PairList<Key, Value>. &id:oatpp::data::mapping::type::PairList; */ template <class Key, class Value> using PairList = oatpp::data::mapping::type::PairList<Key, Value>; /** * Mapping-Enabled PairList<String, Value>. &id:oatpp::data::mapping::type::PairList; */ template <class Value> using Fields = oatpp::PairList<String, Value>; /** * Abstract Fields */ typedef Fields<oatpp::Void> AbstractFields; /** * Mapping-Enabled UnorderedMap<Key, Value>. &id:oatpp::data::mapping::type::UnorderedMap;. */ template <class Key, class Value> using UnorderedMap = oatpp::data::mapping::type::UnorderedMap<Key, Value>; /** * Mapping-Enabled UnorderedMap<String, Value>. &id:oatpp::data::mapping::type::UnorderedMap;. */ template <class Value> using UnorderedFields = oatpp::UnorderedMap<String, Value>; /** * Abstract UnorderedFields */ typedef UnorderedFields<oatpp::Void> AbstractUnorderedFields; } #endif /* oatpp_Types_hpp */
vincent-in-black-sesame/oat
src/oatpp/core/Types.hpp
C++
apache-2.0
6,281
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>, * Matthias Haselmaier <mhaselmaier@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Coroutine.hpp" namespace oatpp { namespace async { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Action Action Action::clone(const Action& action) { Action result(action.m_type); result.m_data = action.m_data; return result; } Action Action::createActionByType(v_int32 type) { return Action(type); } Action Action::createIOWaitAction(v_io_handle ioHandle, Action::IOEventType ioEventType) { Action result(TYPE_IO_WAIT); result.m_data.ioData.ioHandle = ioHandle; result.m_data.ioData.ioEventType = ioEventType; return result; } Action Action::createIORepeatAction(v_io_handle ioHandle, Action::IOEventType ioEventType) { Action result(TYPE_IO_REPEAT); result.m_data.ioData.ioHandle = ioHandle; result.m_data.ioData.ioEventType = ioEventType; return result; } Action Action::createWaitRepeatAction(v_int64 timePointMicroseconds) { Action result(TYPE_WAIT_REPEAT); result.m_data.timePointMicroseconds = timePointMicroseconds; return result; } Action Action::createWaitListAction(CoroutineWaitList* waitList) { Action result(TYPE_WAIT_LIST); result.m_data.waitList = waitList; return result; } Action Action::createWaitListActionWithTimeout(CoroutineWaitList* waitList, const std::chrono::steady_clock::time_point& timeout) { Action result(TYPE_WAIT_LIST_WITH_TIMEOUT); result.m_data.waitListWithTimeout.waitList = waitList; result.m_data.waitListWithTimeout.timeoutTimeSinceEpochMS = std::chrono::duration_cast<std::chrono::milliseconds>(timeout.time_since_epoch()).count(); return result; } Action::Action() : m_type(TYPE_NONE) {} Action::Action(AbstractCoroutine* coroutine) : m_type(TYPE_COROUTINE) { m_data.coroutine = coroutine; } Action::Action(const FunctionPtr& functionPtr) : m_type(TYPE_YIELD_TO) { m_data.fptr = functionPtr; } Action::Action(Error* error) : m_type(TYPE_ERROR) { m_data.error = error; } Action::Action(v_int32 type) : m_type(type) {} Action::Action(Action&& other) : m_type(other.m_type) , m_data(other.m_data) { other.m_type = TYPE_NONE; } Action::~Action() { free(); } void Action::free() { switch(m_type) { case TYPE_COROUTINE: delete m_data.coroutine; break; case TYPE_ERROR: delete m_data.error; break; } m_type = TYPE_NONE; } Action& Action::operator=(Action&& other) { free(); m_type = other.m_type; m_data = other.m_data; other.m_data.fptr = nullptr; return *this; } bool Action::isError() const { return m_type == TYPE_ERROR; } bool Action::isNone() const { return m_type == TYPE_NONE; } v_int32 Action::getType() const { return m_type; } v_int64 Action::getTimePointMicroseconds() const { return m_data.timePointMicroseconds; } oatpp::v_io_handle Action::getIOHandle() const { return m_data.ioData.ioHandle; } Action::IOEventType Action::getIOEventType() const { return m_data.ioData.ioEventType; } v_int32 Action::getIOEventCode() const { return m_type | m_data.ioData.ioEventType; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // CoroutineStarter CoroutineStarter::CoroutineStarter(AbstractCoroutine* coroutine) : m_first(coroutine) , m_last(coroutine) {} CoroutineStarter::CoroutineStarter(CoroutineStarter&& other) : m_first(other.m_first) , m_last(other.m_last) { other.m_first = nullptr; other.m_last = nullptr; } CoroutineStarter::~CoroutineStarter() { freeCoroutines(); } /* * Move assignment operator. */ CoroutineStarter& CoroutineStarter::operator=(CoroutineStarter&& other) { if (this == std::addressof(other)) return *this; freeCoroutines(); m_first = other.m_first; m_last = other.m_last; other.m_first = nullptr; other.m_last = nullptr; return *this; } Action CoroutineStarter::next(Action&& action) { if(m_last == nullptr) { return std::forward<Action>(action); } m_last->m_parentReturnAction = std::forward<Action>(action); Action result = m_first; m_first = nullptr; m_last = nullptr; return result; } CoroutineStarter& CoroutineStarter::next(CoroutineStarter&& starter) { if(m_last == nullptr) { m_first = starter.m_first; m_last = starter.m_last; } else { m_last->m_parentReturnAction = starter.m_first; m_last = starter.m_last; } starter.m_first = nullptr; starter.m_last = nullptr; return *this; } void CoroutineStarter::freeCoroutines() { if (m_first != nullptr) { auto curr = m_first; while (curr != nullptr) { AbstractCoroutine* next = nullptr; if (curr->m_parentReturnAction.m_type == Action::TYPE_COROUTINE) { next = curr->m_parentReturnAction.m_data.coroutine; } delete curr; curr = next; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // CoroutineHandle CoroutineHandle::CoroutineHandle(Processor* processor, AbstractCoroutine* rootCoroutine) : _PP(processor) , _CP(rootCoroutine) , _FP(&AbstractCoroutine::act) , _SCH_A(Action::TYPE_NONE) , _ref(nullptr) {} CoroutineHandle::~CoroutineHandle() { delete _CP; } Action CoroutineHandle::takeAction(Action&& action) { //v_int32 iterations = 0; while (true) { switch (action.m_type) { case Action::TYPE_COROUTINE: { action.m_data.coroutine->m_parent = _CP; action.m_data.coroutine->m_parentReturnFP = _FP; _CP = action.m_data.coroutine; _FP = &AbstractCoroutine::act; action.m_type = Action::TYPE_NONE; return std::forward<oatpp::async::Action>(action); } case Action::TYPE_FINISH: { /* Please note that savedCP->m_parentReturnAction should not be "REPEAT nor WAIT_RETRY" */ /* as funtion pointer (FP) is invalidated */ action = std::move(_CP->m_parentReturnAction); AbstractCoroutine* savedCP = _CP; _FP = _CP->m_parentReturnFP; _CP = _CP->m_parent; delete savedCP; continue; } case Action::TYPE_YIELD_TO: { _FP = action.m_data.fptr; //break; return std::forward<oatpp::async::Action>(action); } // case Action::TYPE_REPEAT: { // break; // } // // case Action::TYPE_IO_REPEAT: { // break; // } case Action::TYPE_ERROR: { Action newAction = _CP->handleError(action.m_data.error); if (newAction.m_type == Action::TYPE_ERROR) { AbstractCoroutine* savedCP = _CP; _CP = _CP->m_parent; delete savedCP; if (newAction.m_data.error == action.m_data.error) { newAction.m_type = Action::TYPE_NONE; } else { action = std::move(newAction); } if(_CP == nullptr) { delete action.m_data.error; action.m_type = Action::TYPE_NONE; return std::forward<oatpp::async::Action>(action); } } else { action = std::move(newAction); } continue; } default: return std::forward<oatpp::async::Action>(action); }; // action = iterate(); // ++ iterations; } return std::forward<oatpp::async::Action>(action); } Action CoroutineHandle::iterate() { try { return _CP->call(_FP); } catch (std::exception& e) { return new Error(e.what()); } catch (...) { return new Error("[oatpp::async::CoroutineHandle::iterate()]: Error. Unknown Exception."); } } Action CoroutineHandle::iterateAndTakeAction() { return takeAction(iterate()); } bool CoroutineHandle::finished() const { return _CP == nullptr; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // AbstractCoroutine AbstractCoroutine::AbstractCoroutine() : m_parent(nullptr) , m_parentReturnAction(Action(Action::TYPE_NONE)) {} Action AbstractCoroutine::handleError(Error* error) { return Action(error); } AbstractCoroutine* AbstractCoroutine::getParent() const { return m_parent; } Action AbstractCoroutine::repeat() { return Action::createActionByType(Action::TYPE_REPEAT); } Action AbstractCoroutine::waitRepeat(const std::chrono::duration<v_int64, std::micro>& timeout) { auto startTime = std::chrono::system_clock::now(); auto end = startTime + timeout; std::chrono::microseconds ms = std::chrono::duration_cast<std::chrono::microseconds>(end.time_since_epoch()); return Action::createWaitRepeatAction(ms.count()); } CoroutineStarter AbstractCoroutine::waitFor(const std::chrono::duration<v_int64, std::micro>& timeout) { class WaitingCoroutine : public Coroutine<WaitingCoroutine> { private: std::chrono::duration<v_int64, std::micro> m_duration; bool m_wait; public: WaitingCoroutine(const std::chrono::duration<v_int64, std::micro>& duration) : m_duration(duration) , m_wait(true) {} Action act() override { if(m_wait) { m_wait = false; return waitRepeat(m_duration); } return finish(); } }; return WaitingCoroutine::start(timeout); } Action AbstractCoroutine::ioWait(v_io_handle ioHandle, Action::IOEventType ioEventType) { return Action::createIOWaitAction(ioHandle, ioEventType); } Action AbstractCoroutine::ioRepeat(v_io_handle ioHandle, Action::IOEventType ioEventType) { return Action::createIORepeatAction(ioHandle, ioEventType); } Action AbstractCoroutine::error(Error* error) { return error; } }}
vincent-in-black-sesame/oat
src/oatpp/core/async/Coroutine.cpp
C++
apache-2.0
10,618
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>, * Matthias Haselmaier <mhaselmaier@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_async_Coroutine_hpp #define oatpp_async_Coroutine_hpp #include "./Error.hpp" #include "oatpp/core/async/utils/FastQueue.hpp" #include "oatpp/core/IODefinitions.hpp" #include "oatpp/core/base/Environment.hpp" #include "oatpp/core/Types.hpp" #include <chrono> #include <exception> namespace oatpp { namespace async { class CoroutineHandle; // FWD class AbstractCoroutine; // FWD class Processor; // FWD class CoroutineStarter; // FWD class CoroutineWaitList; // FWD namespace worker { class Worker; // FWD } /** * Class Action represents an asynchronous action. */ class Action { friend Processor; friend CoroutineHandle; friend AbstractCoroutine; friend CoroutineStarter; friend worker::Worker; public: typedef Action (AbstractCoroutine::*FunctionPtr)(); public: /** * None - invalid Action. */ static constexpr const v_int32 TYPE_NONE = 0; /** * Indicate that Action is to start coroutine. */ static constexpr const v_int32 TYPE_COROUTINE = 1; /** * Indicate that Action is to YIELD control to other method of Coroutine. */ static constexpr const v_int32 TYPE_YIELD_TO = 2; /** * Indicate that Action is to REPEAT call to current method of Coroutine. */ static constexpr const v_int32 TYPE_REPEAT = 3; /** * Indicate that Action is to WAIT for some time and then REPEAT call to current method of Coroutine. */ static constexpr const v_int32 TYPE_WAIT_REPEAT = 4; /** * Indicate that Action is waiting for IO and should be assigned to corresponding worker. */ static constexpr const v_int32 TYPE_IO_WAIT = 5; /** * Indicate that Action is to repeat previously successful I/O operation. */ static constexpr const v_int32 TYPE_IO_REPEAT = 6; /** * Indicate that Action is to FINISH current Coroutine and return control to a caller-Coroutine. */ static constexpr const v_int32 TYPE_FINISH = 7; /** * Indicate that Error occurred. */ static constexpr const v_int32 TYPE_ERROR = 8; /** * Indicate that coroutine should be put on a wait-list provided. */ static constexpr const v_int32 TYPE_WAIT_LIST = 9; /** * Indicate that coroutine should be put on a wait-list provided with a timeout. */ static constexpr const v_int32 TYPE_WAIT_LIST_WITH_TIMEOUT = 10; public: /** * Event type qualifier for Actions of type &l:Action::TYPE_IO_WAIT;, &l:Action::TYPE_IO_REPEAT;. */ enum IOEventType : v_int32 { /** * IO event type READ. */ IO_EVENT_READ = 256, /** * IO event type WRITE. */ IO_EVENT_WRITE = 512 }; /** * Convenience I/O Action Code. * This code is applicable for Action of type TYPE_IO_WAIT only. */ static constexpr const v_int32 CODE_IO_WAIT_READ = TYPE_IO_WAIT | IOEventType::IO_EVENT_READ; /** * Convenience I/O Action Code. * This code is applicable for Action of type TYPE_IO_WAIT only. */ static constexpr const v_int32 CODE_IO_WAIT_WRITE = TYPE_IO_WAIT | IOEventType::IO_EVENT_WRITE; /** * Convenience I/O Action Code. * This code is applicable for Action of type TYPE_IO_WAIT only. */ static constexpr const v_int32 CODE_IO_WAIT_RESCHEDULE = TYPE_IO_WAIT | IOEventType::IO_EVENT_READ | IOEventType::IO_EVENT_WRITE; /** * Convenience I/O Action Code. * This code is applicable for Action of type TYPE_IO_REPEAT only. */ static constexpr const v_int32 CODE_IO_REPEAT_READ = TYPE_IO_REPEAT | IOEventType::IO_EVENT_READ; /** * Convenience I/O Action Code. * This code is applicable for Action of type TYPE_IO_REPEAT only. */ static constexpr const v_int32 CODE_IO_REPEAT_WRITE = TYPE_IO_REPEAT | IOEventType::IO_EVENT_WRITE; /** * Convenience I/O Action Code. * This code is applicable for Action of type TYPE_IO_REPEAT only. */ static constexpr const v_int32 CODE_IO_REPEAT_RESCHEDULE = TYPE_IO_REPEAT | IOEventType::IO_EVENT_READ | IOEventType::IO_EVENT_WRITE; private: struct IOData { oatpp::v_io_handle ioHandle; IOEventType ioEventType; }; struct WaitListWithTimeout { CoroutineWaitList* waitList; v_int64 timeoutTimeSinceEpochMS; }; private: union Data { FunctionPtr fptr; AbstractCoroutine* coroutine; Error* error; IOData ioData; v_int64 timePointMicroseconds; CoroutineWaitList* waitList; WaitListWithTimeout waitListWithTimeout; }; private: mutable v_int32 m_type; Data m_data; private: void free(); protected: /* * Create Action by type. * @param type - Action type. */ Action(v_int32 type); public: /** * Default constructor. */ Action(); /** * Clone action. * @param action - action to clone. * @return - cloned action. */ static Action clone(const Action& action); /** * Create action of specific type * @param type * @return */ static Action createActionByType(v_int32 type); /** * Create TYPE_IO_WAIT Action * @param ioHandle - &id:oatpp::v_io_handle;. * @return - Action. */ static Action createIOWaitAction(v_io_handle ioHandle, IOEventType ioEventType); /** * Create TYPE_IO_REPEAT Action * @param ioHandle - &id:oatpp::v_io_handle;. * @return - Action. */ static Action createIORepeatAction(v_io_handle ioHandle, IOEventType ioEventType); /** * Create TYPE_WAIT_REPEAT Action. * @param timePointMicroseconds - time since epoch. * @return - Action. */ static Action createWaitRepeatAction(v_int64 timePointMicroseconds); /** * Create TYPE_WAIT_LIST Action. * @param waitList - wait-list to put coroutine on. * @return - Action. */ static Action createWaitListAction(CoroutineWaitList* waitList); /** * Create TYPE_WAIT_LIST_WITH_TIMEOUT Action. * @param waitList - wait-list to put coroutine on. * @param timeout - latest time point at which the coroutine should be continued. * @return - Action. */ static Action createWaitListActionWithTimeout(CoroutineWaitList* waitList, const std::chrono::steady_clock::time_point& timeout); /** * Constructor. Create start-coroutine Action. * @param coroutine - pointer to &l:AbstractCoroutine;. */ Action(AbstractCoroutine* coroutine); /** * Constructor. Create yield_to Action. * @param functionPtr - pointer to function. */ Action(const FunctionPtr& functionPtr); /** * Constructor. Create Error Action. * @param error - pointer to &id:oatpp::async::Error;. */ Action(Error* error); /** * Deleted copy-constructor. */ Action(const Action&) = delete; /** * Move-constructor. * @param other */ Action(Action&& other); /** * Non-virtual destructor. */ ~Action(); /* * Deleted copy-assignment operator. */ Action& operator=(const Action&) = delete; /* * Move assignment operator. */ Action& operator=(Action&& other); /** * Check if action is an error reporting action. * @return `true` if action is an error reporting action. */ bool isError() const; /** * Check if action is of TYPE_NONE. * @return */ bool isNone() const; /** * Get Action type. * @return - action type. */ v_int32 getType() const; /** * Get microseconds tick when timer should call coroutine again. * This method returns meaningful value only if Action is TYPE_WAIT_REPEAT. * @return - microseconds tick. */ v_int64 getTimePointMicroseconds() const; /** * Get I/O handle which is passed with this action to I/O worker. * This method returns meaningful value only if Action is TYPE_IO_WAIT or TYPE_IO_REPEAT. * @return - &id:oatpp::v_io_handle;. */ oatpp::v_io_handle getIOHandle() const; /** * This method returns meaningful value only if Action is TYPE_IO_WAIT or TYPE_IO_REPEAT. * @return - should return one of */ IOEventType getIOEventType() const; /** * Convenience method to get I/O Event code. * @return - `getType() | getIOEventType()`. */ v_int32 getIOEventCode() const; }; /** * CoroutineStarter of Coroutine calls. */ class CoroutineStarter { private: AbstractCoroutine* m_first; AbstractCoroutine* m_last; private: void freeCoroutines(); public: /** * Constructor. * @param coroutine - coroutine. */ CoroutineStarter(AbstractCoroutine* coroutine); /** * Deleted copy-constructor. */ CoroutineStarter(const CoroutineStarter&) = delete; /** * Move constructor. * @param other - other starter. */ CoroutineStarter(CoroutineStarter&& other); /** * Non-virtual destructor. */ ~CoroutineStarter(); /* * Deleted copy-assignment operator. */ CoroutineStarter& operator=(const CoroutineStarter&) = delete; /* * Move assignment operator. */ CoroutineStarter& operator=(CoroutineStarter&& other); /** * Set final starter action. * @param action - &l:Action;. * @return - &l:Action;. */ Action next(Action&& action); /** * Pipeline coroutine starter. * @param starter - starter to add. * @return - this starter. */ CoroutineStarter& next(CoroutineStarter&& starter); }; /** * This class manages coroutines processing state and a chain of coroutine calls. */ class CoroutineHandle : public oatpp::base::Countable { friend utils::FastQueue<CoroutineHandle>; friend Processor; friend worker::Worker; friend CoroutineWaitList; public: typedef oatpp::async::Action Action; typedef oatpp::async::Error Error; typedef Action (AbstractCoroutine::*FunctionPtr)(); private: Processor* _PP; AbstractCoroutine* _CP; FunctionPtr _FP; oatpp::async::Action _SCH_A; CoroutineHandle* _ref; public: CoroutineHandle(Processor* processor, AbstractCoroutine* rootCoroutine); ~CoroutineHandle(); Action takeAction(Action&& action); Action iterate(); Action iterateAndTakeAction(); bool finished() const; }; /** * Abstract Coroutine. Base class for Coroutines. It provides state management, coroutines stack management and error reporting functionality. */ class AbstractCoroutine : public oatpp::base::Countable { friend CoroutineStarter; friend CoroutineHandle; public: /** * Convenience typedef for Action */ typedef oatpp::async::Action Action; typedef oatpp::async::Error Error; typedef Action (AbstractCoroutine::*FunctionPtr)(); public: template<typename ...Args> class AbstractMemberCaller { public: virtual ~AbstractMemberCaller() = default; virtual Action call(AbstractCoroutine* coroutine, const Args&... args) = 0; }; template<typename T, typename ...Args> class MemberCaller : public AbstractMemberCaller<Args...> { public: typedef Action (T::*Func)(const Args&...); private: Func m_func; public: MemberCaller(Func func) : m_func(func) {} Action call(AbstractCoroutine* coroutine, const Args&... args) override { T* _this = static_cast<T*>(coroutine); return (_this->*m_func)(args...); } }; template<typename T, typename ...Args> static std::unique_ptr<AbstractMemberCaller<Args...>> createMemberCaller(Action (T::*func)(Args...)) { return std::unique_ptr<AbstractMemberCaller<Args...>>(new MemberCaller<T, Args...>(func)); } private: AbstractCoroutine* m_parent; protected: Action m_parentReturnAction; FunctionPtr m_parentReturnFP; public: /** * Constructor. */ AbstractCoroutine(); /** * Virtual Destructor */ virtual ~AbstractCoroutine() = default; /** * Entrypoint of Coroutine. * @return - Action */ virtual Action act() = 0; /** * Call function of Coroutine specified by ptr.<br> * This method is called from iterate().<br> * Coroutine keeps track of function ptr and calls corresponding function on each iteration. * When Coroutine starts, function ptr points to act(). * @param ptr - pointer of the function to call. * @return - Action. */ virtual Action call(const FunctionPtr& ptr) = 0; /** * Default implementation of handleError(error) function. * User may override this function in order to handle errors. * @param error - &id:oatpp::async::Error;. * @return - Action. If handleError function returns Error, * current coroutine will finish, return control to caller coroutine and handleError is called for caller coroutine. */ virtual Action handleError(Error* error); /** * Get parent coroutine * @return - pointer to a parent coroutine */ AbstractCoroutine* getParent() const; /** * Convenience method to generate Action of `type == Action::TYPE_REPEAT`. * @return - repeat Action. */ static Action repeat(); /** * Convenience method to generate Action of `type == Action::TYPE_WAIT_REPEAT`. * @return - TYPE_WAIT_REPEAT Action. */ static Action waitRepeat(const std::chrono::duration<v_int64, std::micro>& timeout); /** * Wait asynchronously for the specified time. * @return - repeat Action. */ CoroutineStarter waitFor(const std::chrono::duration<v_int64, std::micro>& timeout); /** * Convenience method to generate Action of `type == Action::TYPE_IO_WAIT`. * @return - TYPE_WAIT_FOR_IO Action. */ static Action ioWait(v_io_handle ioHandle, Action::IOEventType ioEventType); /** * Convenience method to generate Action of `type == Action::TYPE_IO_WAIT`. * @return - TYPE_IO_REPEAT Action. */ static Action ioRepeat(v_io_handle ioHandle, Action::IOEventType ioEventType); /** * Convenience method to generate error reporting Action. * @param error - &id:oatpp:async::Error;. * @return - error reporting Action. */ static Action error(Error* error); /** * Convenience method to generate error reporting Action. * @tparam E - Error class type. * @tparam Args - Error constructor arguments. * @param args - actual error constructor arguments. * @return - error reporting &id:oatpp::async::Action;. */ template<class E, typename ... Args> Action error(Args... args) { return error(new E(args...)); } }; /** * Coroutine template. <br> * Example usage:<br> * `class MyCoroutine : public oatpp::async::Coroutine<MyCoroutine>` * @tparam T - child class type */ template<class T> class Coroutine : public AbstractCoroutine { public: typedef Action (T::*Function)(); public: static void* operator new(std::size_t sz) { return ::operator new(sz); } static void operator delete(void* ptr, std::size_t sz) { (void)sz; ::operator delete(ptr); } public: /** * Create coroutine and return it's starter * @tparam ConstructorArgs - coroutine constructor arguments. * @param args - actual coroutine constructor arguments. * @return - &id:oatpp::async::CoroutineStarter;. */ template<typename ...ConstructorArgs> static CoroutineStarter start(ConstructorArgs&&... args) { return new T(std::forward<ConstructorArgs>(args)...); } /** * Call function of Coroutine specified by ptr. <br> * Overridden `AbstractCoroutine::call()` method. * @param ptr - pointer of the function to call. * @return - Action. */ Action call(const FunctionPtr& ptr) override { Function f = static_cast<Function>(ptr); return (static_cast<T*>(this)->*f)(); } /** * Convenience method to generate Action of `type == Action::TYPE_YIELD_TO`. * @param function - pointer to function. * @return - yield Action. */ Action yieldTo(const Function& function) const { return Action(static_cast<FunctionPtr>(function)); } /** * Convenience method to generate Action of `type == Action::TYPE_FINISH`. * @return - finish Action. */ Action finish() const { return Action::createActionByType(Action::TYPE_FINISH); } }; /** * Abstract coroutine with result. */ template<typename ...Args> class AbstractCoroutineWithResult : public AbstractCoroutine { protected: std::unique_ptr<AbstractMemberCaller<Args...>> m_parentMemberCaller; public: /** * Class representing Coroutine call for result; */ class StarterForResult { private: AbstractCoroutineWithResult* m_coroutine; public: /** * Constructor. * @param coroutine - coroutine. */ StarterForResult(AbstractCoroutineWithResult* coroutine) : m_coroutine(coroutine) {} /** * Deleted copy-constructor. */ StarterForResult(const StarterForResult&) = delete; /** * Move constructor. * @param other - other starter. */ StarterForResult(StarterForResult&& other) : m_coroutine(other.m_coroutine) { other.m_coroutine = nullptr; } /** * Non-virtual destructor. */ ~StarterForResult() { delete m_coroutine; } /* * Deleted copy-assignment operator. */ StarterForResult& operator=(const StarterForResult&) = delete; /* * Move assignment operator. */ StarterForResult& operator=(StarterForResult&& other) { if (this == std::addressof(other)) return *this; delete m_coroutine; m_coroutine = other.m_coroutine; other.m_coroutine = nullptr; return *this; } /** * Set callback for result and return coroutine starting Action. * @tparam C - caller coroutine type. * @tparam Args - callback params. * @param callback - callback to obtain result. * @return - &id:oatpp::async::Action;. */ template<typename C> Action callbackTo(Action (C::*callback)(Args...)) { if(m_coroutine == nullptr) { throw std::runtime_error("[oatpp::async::AbstractCoroutineWithResult::StarterForResult::callbackTo()]: Error. Coroutine is null."); } m_coroutine->m_parentMemberCaller = createMemberCaller(callback); Action result = m_coroutine; m_coroutine = nullptr; return result; } }; }; template <typename ...Args> using CoroutineStarterForResult = typename AbstractCoroutineWithResult<Args...>::StarterForResult; /** * Coroutine with result template. <br> * Example usage:<br> * `class CoroutineWithResult : public oatpp::async::CoroutineWithResult<CoroutineWithResult, const char*>` * @tparam T - child class type. * @tparam Args - return argumet type. */ template<class T, typename ...Args> class CoroutineWithResult : public AbstractCoroutineWithResult<Args...> { friend AbstractCoroutine; public: typedef Action (T::*Function)(); public: static void* operator new(std::size_t sz) { return ::operator new(sz); } static void operator delete(void* ptr, std::size_t sz) { (void)sz; ::operator delete(ptr); } public: /** * Call coroutine for result. * @tparam ConstructorArgs - coroutine consrtructor arguments. * @param args - actual constructor arguments. * @return - &l:AbstractCoroutineWithResult::StarterForResult;. */ template<typename ...ConstructorArgs> static CoroutineStarterForResult<Args...> startForResult(ConstructorArgs... args) { return new T(args...); } /** * Call function of Coroutine specified by ptr. <br> * Overridden AbstractCoroutine::call() method. * @param ptr - pointer of the function to call. * @return - Action. */ Action call(const AbstractCoroutine::FunctionPtr& ptr) override { Function f = static_cast<Function>(ptr); return (static_cast<T*>(this)->*f)(); } /** * Convenience method to generate Action of `type == Action::TYPE_YIELD_TO`. * @param function - pointer to function. * @return - yield Action. */ Action yieldTo(const Function& function) const { return Action(static_cast<AbstractCoroutine::FunctionPtr>(function)); } /** * Call caller's Callback passing returned value, and generate Action of `type == Action::TYPE_FINISH`. * @param args - argumets to be passed to callback. * @return - finish Action. */ Action _return(const Args&... args) { this->m_parentReturnAction = this->m_parentMemberCaller->call(this->getParent(), args...); return Action::createActionByType(Action::TYPE_FINISH); } }; }} #endif /* oatpp_async_Coroutine_hpp */
vincent-in-black-sesame/oat
src/oatpp/core/async/Coroutine.hpp
C++
apache-2.0
21,131
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>, * Matthias Haselmaier <mhaselmaier@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "CoroutineWaitList.hpp" #include "./Processor.hpp" #include <algorithm> #include <set> namespace oatpp { namespace async { CoroutineWaitList::CoroutineWaitList(CoroutineWaitList&& other) { { std::lock_guard<oatpp::concurrency::SpinLock> lock{other.m_lock}; m_list = std::move(other.m_list); } { std::lock_guard<oatpp::concurrency::SpinLock> lock{other.m_timeoutsLock}; m_coroutinesWithTimeout = std::move(other.m_coroutinesWithTimeout); m_timeoutCheckingProcessors = std::move(other.m_timeoutCheckingProcessors); for (const std::pair<Processor*, v_int64>& entry : m_timeoutCheckingProcessors) { Processor* processor = entry.first; processor->removeCoroutineWaitListWithTimeouts(std::addressof(other)); processor->addCoroutineWaitListWithTimeouts(this); } } } CoroutineWaitList::~CoroutineWaitList() { notifyAll(); } void CoroutineWaitList::checkCoroutinesForTimeouts() { std::lock_guard<oatpp::concurrency::SpinLock> listLock{m_lock}; std::lock_guard<oatpp::concurrency::SpinLock> lock{m_timeoutsLock}; const auto currentTimeSinceEpochMS = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count(); const auto newEndIt = std::remove_if(std::begin(m_coroutinesWithTimeout), std::end(m_coroutinesWithTimeout), [&](const std::pair<CoroutineHandle*, v_int64>& entry) { return currentTimeSinceEpochMS > entry.second; }); for (CoroutineHandle* curr = m_list.first, *prev = nullptr; !m_list.empty() && m_list.last->_ref != curr; curr = curr->_ref) { const bool removeFromWaitList = std::any_of(newEndIt, std::end(m_coroutinesWithTimeout), [=](const std::pair<CoroutineHandle*, v_int64>& entry) { return entry.first == curr; }); if (!removeFromWaitList) { prev = curr; continue; } m_list.cutEntry(curr, prev); if (--m_timeoutCheckingProcessors[curr->_PP] <= 0) { curr->_PP->removeCoroutineWaitListWithTimeouts(this); m_timeoutCheckingProcessors.erase(curr->_PP); } curr->_PP->pushOneTask(curr); } m_coroutinesWithTimeout.erase(newEndIt, std::end(m_coroutinesWithTimeout)); } void CoroutineWaitList::setListener(Listener* listener) { m_listener = listener; } void CoroutineWaitList::pushFront(CoroutineHandle* coroutine) { { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_lock); m_list.pushFront(coroutine); } if(m_listener != nullptr) { m_listener->onNewItem(*this); } } void CoroutineWaitList::pushFront(CoroutineHandle* coroutine, v_int64 timeoutTimeSinceEpochMS) { { std::lock_guard<oatpp::concurrency::SpinLock> lock{m_timeoutsLock}; m_coroutinesWithTimeout.emplace_back(coroutine, timeoutTimeSinceEpochMS); if (++m_timeoutCheckingProcessors[coroutine->_PP] == 1) { coroutine->_PP->addCoroutineWaitListWithTimeouts(this); } } pushFront(coroutine); } void CoroutineWaitList::pushBack(CoroutineHandle* coroutine) { { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_lock); m_list.pushBack(coroutine); } if(m_listener != nullptr) { m_listener->onNewItem(*this); } } void CoroutineWaitList::pushBack(CoroutineHandle* coroutine, v_int64 timeoutTimeSinceEpochMS) { { std::lock_guard<oatpp::concurrency::SpinLock> lock{m_timeoutsLock}; m_coroutinesWithTimeout.emplace_back(coroutine, timeoutTimeSinceEpochMS); if (++m_timeoutCheckingProcessors[coroutine->_PP] == 1) { coroutine->_PP->addCoroutineWaitListWithTimeouts(this); } } pushBack(coroutine); } void CoroutineWaitList::notifyFirst() { std::lock_guard<oatpp::concurrency::SpinLock> lock{m_lock}; if(m_list.first) { removeFirstCoroutine(); } } void CoroutineWaitList::notifyAll() { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_lock); while (!m_list.empty()) { removeFirstCoroutine(); } } void CoroutineWaitList::removeFirstCoroutine() { auto coroutine = m_list.popFront(); { std::lock_guard<oatpp::concurrency::SpinLock> lock{m_timeoutsLock}; if (--m_timeoutCheckingProcessors[coroutine->_PP] <= 0) { coroutine->_PP->removeCoroutineWaitListWithTimeouts(this); m_timeoutCheckingProcessors.erase(coroutine->_PP); } } coroutine->_PP->pushOneTask(coroutine); } CoroutineWaitList& CoroutineWaitList::operator=(CoroutineWaitList&& other) { if (this == std::addressof(other)) return *this; notifyAll(); { std::lock_guard<oatpp::concurrency::SpinLock> otherLock{other.m_lock}; std::lock_guard<oatpp::concurrency::SpinLock> myLock{m_lock}; m_list = std::move(other.m_list); } { std::lock_guard<oatpp::concurrency::SpinLock> otherLock{other.m_timeoutsLock}; std::lock_guard<oatpp::concurrency::SpinLock> myLock{m_timeoutsLock}; m_coroutinesWithTimeout = std::move(other.m_coroutinesWithTimeout); m_timeoutCheckingProcessors = std::move(other.m_timeoutCheckingProcessors); for (const std::pair<Processor*, v_int64>& entry : m_timeoutCheckingProcessors) { Processor* processor = entry.first; processor->removeCoroutineWaitListWithTimeouts(std::addressof(other)); processor->addCoroutineWaitListWithTimeouts(this); } } return *this; } }}
vincent-in-black-sesame/oat
src/oatpp/core/async/CoroutineWaitList.cpp
C++
apache-2.0
6,340
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>, * Matthias Haselmaier <mhaselmaier@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_async_CoroutineWaitList_hpp #define oatpp_async_CoroutineWaitList_hpp #include "oatpp/core/async/Coroutine.hpp" #include "oatpp/core/async/utils/FastQueue.hpp" #include "oatpp/core/concurrency/SpinLock.hpp" #include <map> #include <mutex> #include <thread> #include <utility> namespace oatpp { namespace async { /** * List of &id:oatpp::async::Coroutine; waiting to be notified. */ class CoroutineWaitList { friend Processor; public: /** * Listener for new items in the wait-list. */ class Listener { public: /** * Default virtual destructor. */ virtual ~Listener() = default; /** * Called when new item is pushed to the list. * @param list - list where new item was pushed to. */ virtual void onNewItem(CoroutineWaitList& list) = 0; }; private: utils::FastQueue<CoroutineHandle> m_list; oatpp::concurrency::SpinLock m_lock; Listener* m_listener = nullptr; std::map<Processor*, v_int64> m_timeoutCheckingProcessors; std::vector<std::pair<CoroutineHandle*, v_int64>> m_coroutinesWithTimeout; oatpp::concurrency::SpinLock m_timeoutsLock; private: void checkCoroutinesForTimeouts(); void removeFirstCoroutine(); protected: /* * Put coroutine on wait-list. * This method should be called by Coroutine Processor only. * @param coroutine */ void pushFront(CoroutineHandle* coroutine); /* * Put coroutine on wait-list with timeout. * This method should be called by Coroutine Processor only. * @param coroutine * @param timeoutTimeSinceEpochMS */ void pushFront(CoroutineHandle* coroutine, v_int64 timeoutTimeSinceEpochMS); /* * Put coroutine on wait-list. * This method should be called by Coroutine Processor only. * @param coroutine */ void pushBack(CoroutineHandle* coroutine); /* * Put coroutine on wait-list with timeout. * This method should be called by Coroutine Processor only. * @param coroutine * @param timeoutTimeSinceEpochMS */ void pushBack(CoroutineHandle* coroutine, v_int64 timeoutTimeSinceEpochMS); public: /** * Deleted copy-constructor. * @param other */ CoroutineWaitList(const CoroutineWaitList&) = delete; CoroutineWaitList& operator=(const CoroutineWaitList&) = delete; public: /** * Default constructor. */ CoroutineWaitList() = default; /** * Move-constructor. * @param other */ CoroutineWaitList(CoroutineWaitList&& other); /** * Virtual destructor. * Will call notifyAllAndClear(). */ virtual ~CoroutineWaitList(); /** * Set wait list listener. <br> * Listener will be called when processor puts coroutine on a wait-list. * @param listener */ void setListener(Listener* listener); /** * Put first-in-list coroutine back to its processor. */ void notifyFirst(); /** * Put all coroutines back to its processors and clear wait-list. */ void notifyAll(); CoroutineWaitList& operator=(CoroutineWaitList&& other); }; }} #endif //oatpp_async_CoroutineWaitList_hpp
vincent-in-black-sesame/oat
src/oatpp/core/async/CoroutineWaitList.hpp
C++
apache-2.0
4,100
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Error.hpp" namespace oatpp { namespace async { Error::Error(const std::string& what) : runtime_error(what) {} }}
vincent-in-black-sesame/oat
src/oatpp/core/async/Error.cpp
C++
apache-2.0
1,125
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_async_Error_hpp #define oatpp_async_Error_hpp #include "oatpp/core/base/Countable.hpp" #include <string> namespace oatpp { namespace async { /** * Class to hold and communicate errors between Coroutines */ class Error : public std::runtime_error, public oatpp::base::Countable { public: /** * Constructor. * @param what - error explanation. */ explicit Error(const std::string& what); /** * Check if error belongs to specified class. * @tparam ErrorClass * @return - `true` if error is of specified class */ template<class ErrorClass> bool is() const { return dynamic_cast<const ErrorClass*>(this) != nullptr; } }; }} #endif //oatpp_async_Error_hpp
vincent-in-black-sesame/oat
src/oatpp/core/async/Error.hpp
C++
apache-2.0
1,707
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Executor.hpp" #include "oatpp/core/async/worker/IOEventWorker.hpp" #include "oatpp/core/async/worker/IOWorker.hpp" #include "oatpp/core/async/worker/TimerWorker.hpp" namespace oatpp { namespace async { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Executor::SubmissionProcessor Executor::SubmissionProcessor::SubmissionProcessor() : worker::Worker(worker::Worker::Type::PROCESSOR) , m_isRunning(true) { m_thread = std::thread(&Executor::SubmissionProcessor::run, this); } oatpp::async::Processor& Executor::SubmissionProcessor::getProcessor() { return m_processor; } void Executor::SubmissionProcessor::run() { while(m_isRunning) { m_processor.waitForTasks(); while (m_processor.iterate(100)) {} } } void Executor::SubmissionProcessor::pushTasks(utils::FastQueue<CoroutineHandle>& tasks) { (void)tasks; throw std::runtime_error("[oatpp::async::Executor::SubmissionProcessor::pushTasks]: Error. This method does nothing."); } void Executor::SubmissionProcessor::pushOneTask(CoroutineHandle* task) { (void)task; throw std::runtime_error("[oatpp::async::Executor::SubmissionProcessor::pushOneTask]: Error. This method does nothing."); } void Executor::SubmissionProcessor::stop() { m_isRunning = false; m_processor.stop(); } void Executor::SubmissionProcessor::join() { m_thread.join(); } void Executor::SubmissionProcessor::detach() { m_thread.detach(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Executor Executor::Executor(v_int32 processorWorkersCount, v_int32 ioWorkersCount, v_int32 timerWorkersCount, v_int32 ioWorkerType) : m_balancer(0) { processorWorkersCount = chooseProcessorWorkersCount(processorWorkersCount); ioWorkersCount = chooseIOWorkersCount(processorWorkersCount, ioWorkersCount); timerWorkersCount = chooseTimerWorkersCount(timerWorkersCount); ioWorkerType = chooseIOWorkerType(ioWorkerType); for(v_int32 i = 0; i < processorWorkersCount; i ++) { m_processorWorkers.push_back(std::make_shared<SubmissionProcessor>()); } m_allWorkers.insert(m_allWorkers.end(), m_processorWorkers.begin(), m_processorWorkers.end()); std::vector<std::shared_ptr<worker::Worker>> ioWorkers; ioWorkers.reserve(ioWorkersCount); switch(ioWorkerType) { case IO_WORKER_TYPE_NAIVE: { for (v_int32 i = 0; i < ioWorkersCount; i++) { ioWorkers.push_back(std::make_shared<worker::IOWorker>()); } break; } case IO_WORKER_TYPE_EVENT: { for (v_int32 i = 0; i < ioWorkersCount; i++) { ioWorkers.push_back(std::make_shared<worker::IOEventWorkerForeman>()); } break; } default: throw std::runtime_error("[oatpp::async::Executor::Executor()]: Error. Unknown IO worker type."); } linkWorkers(ioWorkers); std::vector<std::shared_ptr<worker::Worker>> timerWorkers; timerWorkers.reserve(timerWorkersCount); for(v_int32 i = 0; i < timerWorkersCount; i++) { timerWorkers.push_back(std::make_shared<worker::TimerWorker>()); } linkWorkers(timerWorkers); } v_int32 Executor::chooseProcessorWorkersCount(v_int32 processorWorkersCount) { if(processorWorkersCount >= 1) { return processorWorkersCount; } if(processorWorkersCount == VALUE_SUGGESTED) { return oatpp::concurrency::getHardwareConcurrency(); } throw std::runtime_error("[oatpp::async::Executor::chooseProcessorWorkersCount()]: Error. Invalid processor workers count specified."); } v_int32 Executor::chooseIOWorkersCount(v_int32 processorWorkersCount, v_int32 ioWorkersCount) { if(ioWorkersCount >= 1) { return ioWorkersCount; } if(ioWorkersCount == VALUE_SUGGESTED) { v_int32 count = processorWorkersCount >> 1; if(count == 0) { count = 1; } return count; } throw std::runtime_error("[oatpp::async::Executor::chooseIOWorkersCount()]: Error. Invalid I/O workers count specified."); } v_int32 Executor::chooseTimerWorkersCount(v_int32 timerWorkersCount) { if(timerWorkersCount >= 1) { return timerWorkersCount; } if(timerWorkersCount == VALUE_SUGGESTED) { return 1; } throw std::runtime_error("[oatpp::async::Executor::chooseTimerWorkersCount()]: Error. Invalid timer workers count specified."); } v_int32 Executor::chooseIOWorkerType(v_int32 ioWorkerType) { if(ioWorkerType == VALUE_SUGGESTED) { #if defined(OATPP_IO_EVENT_INTERFACE_STUB) return IO_WORKER_TYPE_NAIVE; #else return IO_WORKER_TYPE_EVENT; #endif } return ioWorkerType; } void Executor::linkWorkers(const std::vector<std::shared_ptr<worker::Worker>>& workers) { m_allWorkers.insert(m_allWorkers.end(), workers.begin(), workers.end()); if(m_processorWorkers.size() > workers.size() && (m_processorWorkers.size() % workers.size()) == 0) { size_t wi = 0; for(auto & p : m_processorWorkers) { p->getProcessor().addWorker(workers[wi]); wi ++; if(wi == workers.size()) { wi = 0; } } } else if ((workers.size() % m_processorWorkers.size()) == 0) { size_t pi = 0; for(const auto & worker : workers) { auto& p = m_processorWorkers[pi]; p->getProcessor().addWorker(worker); pi ++; if(pi == m_processorWorkers.size()) { pi = 0; } } } else { for(auto & p : m_processorWorkers) { for(auto& w : workers) { p->getProcessor().addWorker(w); } } } } void Executor::join() { for(auto& worker : m_allWorkers) { worker->join(); } } void Executor::detach() { for(auto& worker : m_allWorkers) { worker->detach(); } } void Executor::stop() { for(auto& worker : m_allWorkers) { worker->stop(); } } v_int32 Executor::getTasksCount() { v_int32 result = 0; for(const auto& procWorker : m_processorWorkers) { result += procWorker->getProcessor().getTasksCount(); } return result; } void Executor::waitTasksFinished(const std::chrono::duration<v_int64, std::micro>& timeout) { auto startTime = std::chrono::system_clock::now(); while(getTasksCount() != 0) { auto elapsed = std::chrono::system_clock::now() - startTime; if(elapsed < timeout) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } else { break; } } } }}
vincent-in-black-sesame/oat
src/oatpp/core/async/Executor.cpp
C++
apache-2.0
7,371
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_async_Executor_hpp #define oatpp_async_Executor_hpp #include "./Processor.hpp" #include "oatpp/core/async/worker/Worker.hpp" #include "oatpp/core/concurrency/SpinLock.hpp" #include "oatpp/core/concurrency/Thread.hpp" #include <tuple> #include <mutex> #include <condition_variable> namespace oatpp { namespace async { /** * Asynchronous Executor.<br> * Executes coroutines in multiple &id:oatpp::async::Processor; * allocating one thread per processor. */ class Executor { private: class SubmissionProcessor : public worker::Worker { private: oatpp::async::Processor m_processor; private: std::atomic<bool> m_isRunning; private: std::thread m_thread; public: SubmissionProcessor(); public: template<typename CoroutineType, typename ... Args> void execute(Args... params) { m_processor.execute<CoroutineType, Args...>(params...); } oatpp::async::Processor& getProcessor(); void pushTasks(utils::FastQueue<CoroutineHandle>& tasks) override; void pushOneTask(CoroutineHandle* task) override; void run(); void stop() override; void join() override; void detach() override; }; public: /** * Special value to indicate that Executor should choose it's own the value of specified parameter. */ static constexpr const v_int32 VALUE_SUGGESTED = -1000; public: /** * IO Worker type naive. */ static constexpr const v_int32 IO_WORKER_TYPE_NAIVE = 0; /** * IO Worker type event. */ static constexpr const v_int32 IO_WORKER_TYPE_EVENT = 1; private: std::atomic<v_uint32> m_balancer; private: std::vector<std::shared_ptr<SubmissionProcessor>> m_processorWorkers; std::vector<std::shared_ptr<worker::Worker>> m_allWorkers; private: static v_int32 chooseProcessorWorkersCount(v_int32 processorWorkersCount); static v_int32 chooseIOWorkersCount(v_int32 processorWorkersCount, v_int32 ioWorkersCount); static v_int32 chooseTimerWorkersCount(v_int32 timerWorkersCount); static v_int32 chooseIOWorkerType(v_int32 ioWorkerType); void linkWorkers(const std::vector<std::shared_ptr<worker::Worker>>& workers); public: /** * Constructor. * @param processorWorkersCount - number of data processing workers. * @param ioWorkersCount - number of I/O processing workers. * @param timerWorkersCount - number of timer processing workers. * @param IOWorkerType */ Executor(v_int32 processorWorkersCount = VALUE_SUGGESTED, v_int32 ioWorkersCount = VALUE_SUGGESTED, v_int32 timerWorkersCount = VALUE_SUGGESTED, v_int32 ioWorkerType = VALUE_SUGGESTED); /** * Non-virtual Destructor. */ ~Executor() = default; /** * Join all worker-threads. */ void join(); /** * Detach all worker-threads. */ void detach(); /** * Stop Executor. <br> * After all worker-threads are stopped. Join should unblock. */ void stop(); /** * Execute Coroutine. * @tparam CoroutineType - type of coroutine to execute. * @tparam Args - types of arguments to be passed to Coroutine constructor. * @param params - actual arguments to be passed to Coroutine constructor. */ template<typename CoroutineType, typename ... Args> void execute(Args... params) { auto& processor = m_processorWorkers[(++ m_balancer) % m_processorWorkers.size()]; processor->execute<CoroutineType, Args...>(params...); } /** * Get number of all not finished tasks. * @return - number of all not finished tasks. */ v_int32 getTasksCount(); /** * Wait until all tasks are finished. * @param timeout */ void waitTasksFinished(const std::chrono::duration<v_int64, std::micro>& timeout = std::chrono::minutes(1)); }; }} #endif /* oatpp_async_Executor_hpp */
vincent-in-black-sesame/oat
src/oatpp/core/async/Executor.hpp
C++
apache-2.0
4,791
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Lock.hpp" namespace oatpp { namespace async { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Lock Lock::Lock() : m_counter(0) { m_list.setListener(this); } void Lock::onNewItem(CoroutineWaitList& list) { auto counter = m_counter.load(); if(counter == 0) { list.notifyFirst(); } else if(counter < 0) { throw std::runtime_error("[oatpp::async::Lock::onNewItem()]: Error. Invalid state."); } } Action Lock::waitAsync() { auto counter = m_counter.load(); if(counter > 0) { return Action::createWaitListAction(&m_list); } else if(counter == 0) { return Action::createActionByType(Action::TYPE_REPEAT); } throw std::runtime_error("[oatpp::async::Lock::waitAsync()]: Error. Invalid state."); } void Lock::lock() { m_mutex.lock(); ++ m_counter; } void Lock::unlock() { m_mutex.unlock(); -- m_counter; if(m_counter < 0) { throw std::runtime_error("[oatpp::async::Lock::unlock()]: Error. Invalid state."); } m_list.notifyFirst(); } bool Lock::try_lock() { bool result = m_mutex.try_lock(); if(result) { ++ m_counter; } return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // LockGuard LockGuard::LockGuard() : m_ownsLock(false) , m_lock(nullptr) {} LockGuard::LockGuard(Lock* lock) : m_ownsLock(false) , m_lock(lock) {} LockGuard::~LockGuard() { if(m_ownsLock) { m_lock->unlock(); } } void LockGuard::setLockObject(Lock* lock) { if(m_lock == nullptr) { m_lock = lock; } else if(m_lock != lock) { throw std::runtime_error("[oatpp::async::LockGuard::setLockObject()]: Error. Invalid state. LockGuard is NOT reusable."); } } CoroutineStarter LockGuard::lockAsync() { class LockCoroutine : public Coroutine<LockCoroutine> { private: LockGuard* m_guard; public: LockCoroutine(LockGuard* guard) : m_guard(guard) {} Action act() override { return m_guard->lockAsyncInline(finish()); } }; return LockCoroutine::start(this); } CoroutineStarter LockGuard::lockAsync(Lock* lock) { setLockObject(lock); return lockAsync(); } Action LockGuard::lockAsyncInline(oatpp::async::Action&& nextAction) { if(!m_ownsLock) { m_ownsLock = m_lock->try_lock(); if(m_ownsLock) { return std::forward<Action>(nextAction); } else { return m_lock->waitAsync(); } } else { throw std::runtime_error("[oatpp::async::LockGuard::lockAsyncInline()]: Error. Invalid state. Double lock attempt."); } } void LockGuard::unlock() { if(m_lock) { if(m_ownsLock) { m_lock->unlock(); m_ownsLock = false; } else { throw std::runtime_error("[oatpp::async::LockGuard::unlock()]: Error. Invalid state. LockGuard is NOT owning the lock."); } } else { throw std::runtime_error("[oatpp::async::LockGuard::unlock()]: Error. Invalid state. Lock object is nullptr."); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Misc CoroutineStarter synchronize(oatpp::async::Lock *lock, CoroutineStarter&& starter) { class Synchronized : public oatpp::async::Coroutine<Synchronized> { private: oatpp::async::LockGuard m_lockGuard; CoroutineStarter m_starter; public: Synchronized(oatpp::async::Lock *lock, CoroutineStarter&& starter) : m_lockGuard(lock) , m_starter(std::forward<CoroutineStarter>(starter)) {} Action act() override { return m_lockGuard.lockAsync().next(std::move(m_starter)).next(finish()); } }; return new Synchronized(lock, std::forward<CoroutineStarter>(starter)); } }}
vincent-in-black-sesame/oat
src/oatpp/core/async/Lock.cpp
C++
apache-2.0
4,781
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_async_Mutex_hpp #define oatpp_async_Mutex_hpp #include "./CoroutineWaitList.hpp" namespace oatpp { namespace async { /** * Lock (mutex) for coroutines/threads synchronization. <br> * - When called from a thread - must be used with `std::lock_guard`. * - When called from coroutine - must be used with &l:LockGuard;. */ class Lock : private CoroutineWaitList::Listener { private: std::atomic<v_int32> m_counter; std::mutex m_mutex; CoroutineWaitList m_list; private: void onNewItem(CoroutineWaitList& list) override; public: /** * Constructor. */ Lock(); /** * Wait until lock is unlocked, and repeat. * @return - &id:oatpp::async::Action;. */ Action waitAsync(); /** * Lock on current thread. !Should NOT be called from within the Coroutine! */ void lock(); /** * Unlock */ void unlock(); /** * Try to lock. * @return - `true` if the lock was acquired, `false` otherwise. */ bool try_lock(); }; /** * Asynchronous lock guard. <br> * Should be used as a lock guard in coroutines. */ class LockGuard { public: /** * Convenince typedef for &id:oatpp::async::CoroutineStarter;. */ typedef oatpp::async::CoroutineStarter CoroutineStarter; private: bool m_ownsLock; Lock* m_lock; public: LockGuard(const LockGuard&) = delete; LockGuard& operator = (const LockGuard&) = delete; public: /** * Default constructor. */ LockGuard(); /** * Constructor with lock. */ LockGuard(Lock* lock); /** * Non-virtual destructor. <br> * Will unlock the Lock if owns lock. */ ~LockGuard(); /** * Set lock object. * @param lock - lock object. */ void setLockObject(Lock* lock); /** * Lock the lock. * @return - &id:oatpp::async::CoroutineStarter;. */ CoroutineStarter lockAsync(); /** * Lock and guard the lock. <br> * Same as `setLockObject(lock) + lockAsync();`. * @param lock - lock to lock and guard. * @return - &id:oatpp::async::CoroutineStarter;. */ CoroutineStarter lockAsync(Lock* lock); /** * Lock the lock. (Async-inline usage. Should be called from a separate method of coroutine). * @param nextAction - action to take after lock is locked. * @return - &id:oatpp::async::Action;. */ Action lockAsyncInline(oatpp::async::Action&& nextAction); /** * Unlock guarded lock. */ void unlock(); }; /** * Synchronize coroutine execution by lock. * @param lock - &l:Lock; for synchronization. * @param starter - Coroutine to execute in synchronized manner. &id:oatpp::async::CoroutineStarter;. * @return - starter of synchronization coroutine (wrapper coroutine). &id:oatpp::async::CoroutineStarter;. */ CoroutineStarter synchronize(oatpp::async::Lock *lock, CoroutineStarter&& starter); }} #endif // oatpp_async_Mutex_hpp
vincent-in-black-sesame/oat
src/oatpp/core/async/Lock.hpp
C++
apache-2.0
3,830
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>, * Matthias Haselmaier <mhaselmaier@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Processor.hpp" #include "./CoroutineWaitList.hpp" #include "oatpp/core/async/worker/Worker.hpp" namespace oatpp { namespace async { void Processor::checkCoroutinesForTimeouts() { while (m_running) { { std::unique_lock<std::recursive_mutex> lock{m_coroutineWaitListsWithTimeoutsMutex}; while (m_coroutineWaitListsWithTimeouts.empty()) { m_coroutineWaitListsWithTimeoutsCV.wait(lock); if (!m_running) return; } const auto coroutineWaitListsWithTimeouts = m_coroutineWaitListsWithTimeouts; for (CoroutineWaitList* waitList : coroutineWaitListsWithTimeouts) { waitList->checkCoroutinesForTimeouts(); } } std::this_thread::sleep_for(std::chrono::milliseconds{100}); } } void Processor::addCoroutineWaitListWithTimeouts(CoroutineWaitList* waitList) { { std::lock_guard<std::recursive_mutex> lock{m_coroutineWaitListsWithTimeoutsMutex}; m_coroutineWaitListsWithTimeouts.insert(waitList); } m_coroutineWaitListsWithTimeoutsCV.notify_one(); } void Processor::removeCoroutineWaitListWithTimeouts(CoroutineWaitList* waitList) { std::lock_guard<std::recursive_mutex> lock{m_coroutineWaitListsWithTimeoutsMutex}; m_coroutineWaitListsWithTimeouts.erase(waitList); } void Processor::addWorker(const std::shared_ptr<worker::Worker>& worker) { switch(worker->getType()) { case worker::Worker::Type::IO: m_ioWorkers.push_back(worker); m_ioPopQueues.push_back(utils::FastQueue<CoroutineHandle>()); break; case worker::Worker::Type::TIMER: m_timerWorkers.push_back(worker); m_timerPopQueues.push_back(utils::FastQueue<CoroutineHandle>()); break; default: break; } } void Processor::popIOTask(CoroutineHandle* coroutine) { if(m_ioPopQueues.size() > 0) { auto &queue = m_ioPopQueues[(++m_ioBalancer) % m_ioPopQueues.size()]; queue.pushBack(coroutine); //m_ioWorkers[(++m_ioBalancer) % m_ioWorkers.size()]->pushOneTask(coroutine); } else { throw std::runtime_error("[oatpp::async::Processor::popIOTasks()]: Error. Processor has no I/O workers."); } } void Processor::popTimerTask(CoroutineHandle* coroutine) { if(m_timerPopQueues.size() > 0) { auto &queue = m_timerPopQueues[(++m_timerBalancer) % m_timerPopQueues.size()]; queue.pushBack(coroutine); //m_timerWorkers[(++m_timerBalancer) % m_timerWorkers.size()]->pushOneTask(coroutine); } else { throw std::runtime_error("[oatpp::async::Processor::popTimerTask()]: Error. Processor has no Timer workers."); } } void Processor::addCoroutine(CoroutineHandle* coroutine) { if(coroutine->_PP == this) { const Action& action = coroutine->takeAction(std::move(coroutine->_SCH_A)); switch(action.m_type) { case Action::TYPE_IO_REPEAT: coroutine->_SCH_A = Action::clone(action); popIOTask(coroutine); break; case Action::TYPE_IO_WAIT: coroutine->_SCH_A = Action::clone(action); popIOTask(coroutine); break; case Action::TYPE_WAIT_REPEAT: coroutine->_SCH_A = Action::clone(action); popTimerTask(coroutine); break; case Action::TYPE_WAIT_LIST: coroutine->_SCH_A = Action::createActionByType(Action::TYPE_NONE); action.m_data.waitList->pushBack(coroutine); break; case Action::TYPE_WAIT_LIST_WITH_TIMEOUT: coroutine->_SCH_A = Action::createActionByType(Action::TYPE_NONE); action.m_data.waitListWithTimeout.waitList->pushBack(coroutine, action.m_data.waitListWithTimeout.timeoutTimeSinceEpochMS); break; default: m_queue.pushBack(coroutine); } } else { throw std::runtime_error("[oatpp::async::processor::addTask()]: Error. Attempt to schedule coroutine to wrong processor."); } } void Processor::pushOneTask(CoroutineHandle* coroutine) { { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_taskLock); m_pushList.pushBack(coroutine); } m_taskCondition.notify_one(); } void Processor::pushTasks(utils::FastQueue<CoroutineHandle>& tasks) { { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_taskLock); utils::FastQueue<CoroutineHandle>::moveAll(tasks, m_pushList); } m_taskCondition.notify_one(); } void Processor::waitForTasks() { std::unique_lock<oatpp::concurrency::SpinLock> lock(m_taskLock); while (m_pushList.first == nullptr && m_taskList.empty() && m_running) { m_taskCondition.wait(lock); } } void Processor::popTasks() { for(size_t i = 0; i < m_ioWorkers.size(); i++) { auto& worker = m_ioWorkers[i]; auto& popQueue = m_ioPopQueues[i]; worker->pushTasks(popQueue); } for(size_t i = 0; i < m_timerWorkers.size(); i++) { auto& worker = m_timerWorkers[i]; auto& popQueue = m_timerPopQueues[i]; worker->pushTasks(popQueue); } } void Processor::consumeAllTasks() { for(auto& submission : m_taskList) { m_queue.pushBack(submission->createCoroutine(this)); } m_taskList.clear(); } void Processor::pushQueues() { utils::FastQueue<CoroutineHandle> tmpList; { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_taskLock); consumeAllTasks(); utils::FastQueue<CoroutineHandle>::moveAll(m_pushList, tmpList); } while(tmpList.first != nullptr) { addCoroutine(tmpList.popFront()); } } bool Processor::iterate(v_int32 numIterations) { pushQueues(); for(v_int32 i = 0; i < numIterations; i++) { auto CP = m_queue.first; if (CP == nullptr) { break; } if (CP->finished()) { m_queue.popFrontNoData(); -- m_tasksCounter; } else { const Action &action = CP->iterateAndTakeAction(); switch (action.m_type) { case Action::TYPE_IO_WAIT: CP->_SCH_A = Action::clone(action); m_queue.popFront(); popIOTask(CP); break; case Action::TYPE_WAIT_REPEAT: CP->_SCH_A = Action::clone(action); m_queue.popFront(); popTimerTask(CP); break; case Action::TYPE_WAIT_LIST: CP->_SCH_A = Action::createActionByType(Action::TYPE_NONE); m_queue.popFront(); action.m_data.waitList->pushBack(CP); break; case Action::TYPE_WAIT_LIST_WITH_TIMEOUT: CP->_SCH_A = Action::createActionByType(Action::TYPE_NONE); m_queue.popFront(); action.m_data.waitListWithTimeout.waitList->pushBack(CP, action.m_data.waitListWithTimeout.timeoutTimeSinceEpochMS); break; default: m_queue.round(); } } } popTasks(); std::lock_guard<oatpp::concurrency::SpinLock> lock(m_taskLock); return m_queue.first != nullptr || m_pushList.first != nullptr || !m_taskList.empty(); } void Processor::stop() { { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_taskLock); m_running = false; } m_taskCondition.notify_one(); m_coroutineWaitListsWithTimeoutsCV.notify_one(); m_coroutineWaitListTimeoutChecker.join(); } v_int32 Processor::getTasksCount() { return m_tasksCounter.load(); } }}
vincent-in-black-sesame/oat
src/oatpp/core/async/Processor.cpp
C++
apache-2.0
8,156
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>, * Matthias Haselmaier <mhaselmaier@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_async_Processor_hpp #define oatpp_async_Processor_hpp #include "./Coroutine.hpp" #include "./CoroutineWaitList.hpp" #include "oatpp/core/async/utils/FastQueue.hpp" #include <condition_variable> #include <list> #include <mutex> #include <set> #include <vector> namespace oatpp { namespace async { /** * Asynchronous Processor.<br> * Responsible for processing and managing multiple Coroutines. * Do not use bare processor to run coroutines. Use &id:oatpp::async::Executor; instead;. */ class Processor { friend class CoroutineWaitList; private: class TaskSubmission { public: virtual ~TaskSubmission() = default; virtual CoroutineHandle* createCoroutine(Processor* processor) = 0; }; /* * Sequence generating templates * used to convert tuple to parameters pack * Example: expand SequenceGenerator<3>: * // 2, 2, {} // 1, 1, {2} // 0, 0, {1, 2} // 0, {0, 1, 2} * where {...} is int...S */ template<int ...> struct IndexSequence {}; template<int N, int ...S> struct SequenceGenerator : SequenceGenerator <N - 1, N - 1, S...> {}; template<int ...S> struct SequenceGenerator<0, S...> { typedef IndexSequence<S...> type; }; template<typename CoroutineType, typename ... Args> class SubmissionTemplate : public TaskSubmission { private: std::tuple<Args...> m_params; public: SubmissionTemplate(Args... params) : m_params(std::make_tuple(params...)) {} virtual CoroutineHandle* createCoroutine(Processor* processor) { return creator(processor, typename SequenceGenerator<sizeof...(Args)>::type()); } template<int ...S> CoroutineHandle* creator(Processor* processor, IndexSequence<S...>) { return new CoroutineHandle(processor, new CoroutineType(std::get<S>(m_params) ...)); } }; private: std::vector<std::shared_ptr<worker::Worker>> m_ioWorkers; std::vector<std::shared_ptr<worker::Worker>> m_timerWorkers; std::vector<utils::FastQueue<CoroutineHandle>> m_ioPopQueues; std::vector<utils::FastQueue<CoroutineHandle>> m_timerPopQueues; v_uint32 m_ioBalancer = 0; v_uint32 m_timerBalancer = 0; private: oatpp::concurrency::SpinLock m_taskLock; std::condition_variable_any m_taskCondition; std::list<std::shared_ptr<TaskSubmission>> m_taskList; utils::FastQueue<CoroutineHandle> m_pushList; private: utils::FastQueue<CoroutineHandle> m_queue; private: std::atomic_bool m_running{true}; std::atomic<v_int32> m_tasksCounter{0}; private: std::recursive_mutex m_coroutineWaitListsWithTimeoutsMutex; std::condition_variable_any m_coroutineWaitListsWithTimeoutsCV; std::set<CoroutineWaitList*> m_coroutineWaitListsWithTimeouts; std::thread m_coroutineWaitListTimeoutChecker{&Processor::checkCoroutinesForTimeouts, this}; void checkCoroutinesForTimeouts(); void addCoroutineWaitListWithTimeouts(CoroutineWaitList* waitList); void removeCoroutineWaitListWithTimeouts(CoroutineWaitList* waitList); private: void popIOTask(CoroutineHandle* coroutine); void popTimerTask(CoroutineHandle* coroutine); void consumeAllTasks(); void addCoroutine(CoroutineHandle* coroutine); void popTasks(); void pushQueues(); public: Processor() = default; /** * Add dedicated co-worker to processor. * @param worker - &id:oatpp::async::worker::Worker;. */ void addWorker(const std::shared_ptr<worker::Worker>& worker); /** * Push one Coroutine back to processor. * @param coroutine - &id:oatpp::async::CoroutineHandle; previously popped-out(rescheduled to coworker) from this processor. */ void pushOneTask(CoroutineHandle* coroutine); /** * Push list of Coroutines back to processor. * @param tasks - &id:oatpp::async::utils::FastQueue; of &id:oatpp::async::CoroutineHandle; previously popped-out(rescheduled to coworker) from this processor. */ void pushTasks(utils::FastQueue<CoroutineHandle>& tasks); /** * Execute Coroutine. * @tparam CoroutineType - type of coroutine to execute. * @tparam Args - types of arguments to be passed to Coroutine constructor. * @param params - actual arguments to be passed to Coroutine constructor. */ template<typename CoroutineType, typename ... Args> void execute(Args... params) { auto submission = std::make_shared<SubmissionTemplate<CoroutineType, Args...>>(params...); ++ m_tasksCounter; { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_taskLock); m_taskList.push_back(submission); } m_taskCondition.notify_one(); } /** * Sleep and wait for tasks. */ void waitForTasks(); /** * Iterate Coroutines. * @param numIterations - number of iterations. * @return - `true` if there are active Coroutines. */ bool iterate(v_int32 numIterations); /** * Stop waiting for new tasks. */ void stop(); /** * Get number of all not-finished tasks including tasks rescheduled for processor's co-workers. * @return - number of not-finished tasks. */ v_int32 getTasksCount(); }; }} #endif /* oatpp_async_Processor_hpp */
vincent-in-black-sesame/oat
src/oatpp/core/async/Processor.hpp
C++
apache-2.0
6,125
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_async_utils_FastQueue_hpp #define oatpp_async_utils_FastQueue_hpp #include "oatpp/core/concurrency/SpinLock.hpp" #include "oatpp/core/base/Environment.hpp" namespace oatpp { namespace async { namespace utils { template<typename T> class FastQueue { public: FastQueue() : first(nullptr) , last(nullptr) , count(0) {} ~FastQueue(){ clear(); } FastQueue(const FastQueue &) = delete; FastQueue(FastQueue &&other) noexcept : FastQueue() { using std::swap; swap(first, other.first); swap(last, other.last); swap(count, other.count); } FastQueue &operator=(const FastQueue &) = delete; FastQueue &operator=(FastQueue &&other) noexcept { if (this != std::addressof(other)) { using std::swap; swap(first, other.first); swap(last, other.last); swap(count, other.count); } return *this; } T* first; T* last; v_int32 count{}; v_int32 Count() { return count; } bool empty() { return count == 0; } void pushFront(T* entry) { entry->_ref = first; first = entry; if(last == nullptr) { last = first; } ++ count; } void pushBack(T* entry) { entry->_ref = nullptr; if(last == nullptr) { first = entry; last = entry; } else { last->_ref = entry; last = entry; } ++ count; } void round(){ if(count > 1) { last->_ref = first; last = first; first = first->_ref; last->_ref = nullptr; } } T* popFront() { T* result = first; first = first->_ref; if(first == nullptr) { last = nullptr; } -- count; return result; } void popFrontNoData() { T* result = first; first = first->_ref; if(first == nullptr) { last = nullptr; } delete result; -- count; } static void moveAll(FastQueue& fromQueue, FastQueue& toQueue) { if(fromQueue.count > 0) { if (toQueue.last == nullptr) { toQueue.first = fromQueue.first; toQueue.last = fromQueue.last; } else { toQueue.last->_ref = fromQueue.first; toQueue.last = fromQueue.last; } toQueue.count += fromQueue.count; fromQueue.count = 0; fromQueue.first = nullptr; fromQueue.last = nullptr; } } void cutEntry(T* entry, T* prevEntry){ if(prevEntry == nullptr) { popFront(); } else { prevEntry->_ref = entry->_ref; -- count; if(prevEntry->_ref == nullptr) { last = prevEntry; } } } void clear() { T* curr = first; while (curr != nullptr) { T* next = curr->_ref; delete curr; curr = next; } first = nullptr; last = nullptr; count = 0; } }; }}} #endif /* oatpp_async_utils_FastQueue_hpp */
vincent-in-black-sesame/oat
src/oatpp/core/async/utils/FastQueue.hpp
C++
apache-2.0
3,871
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_async_worker_IOEventWorker_hpp #define oatpp_async_worker_IOEventWorker_hpp #include "./Worker.hpp" #include "oatpp/core/concurrency/SpinLock.hpp" #include <thread> #include <mutex> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(OATPP_IO_EVENT_INTERFACE) #if defined(__linux__) || defined(linux) || defined(__linux) #define OATPP_IO_EVENT_INTERFACE "epoll" #define OATPP_IO_EVENT_INTERFACE_EPOLL #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ defined(__bsdi__) || defined(__DragonFly__)|| defined(__APPLE__) #define OATPP_IO_EVENT_INTERFACE "kqueue" #define OATPP_IO_EVENT_INTERFACE_KQUEUE #else #define OATPP_IO_EVENT_INTERFACE "not-implemented(windows)" #define OATPP_IO_EVENT_INTERFACE_STUB #endif #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace oatpp { namespace async { namespace worker { class IOEventWorkerForeman; // FWD /** * Event-based implementation of I/O worker. * <ul> * <li>`kqueue` based implementation - for Mac/BSD systems</li> * <li>`epoll` based implementation - for Linux systems</li> * </ul> */ class IOEventWorker : public Worker { private: static constexpr const v_int32 MAX_EVENTS = 10000; private: IOEventWorkerForeman* m_foreman; Action::IOEventType m_specialization; std::atomic<bool> m_running; utils::FastQueue<CoroutineHandle> m_backlog; oatpp::concurrency::SpinLock m_backlogLock; private: oatpp::v_io_handle m_eventQueueHandle; oatpp::v_io_handle m_wakeupTrigger; std::unique_ptr<v_char8[]> m_inEvents; v_int32 m_inEventsCount; v_int32 m_inEventsCapacity; std::unique_ptr<v_char8[]> m_outEvents; private: std::thread m_thread; private: void consumeBacklog(); void waitEvents(); private: void initEventQueue(); void triggerWakeup(); void setTriggerEvent(p_char8 eventPtr); void setCoroutineEvent(CoroutineHandle* coroutine, int operation, p_char8 eventPtr); public: /** * Constructor. */ IOEventWorker(IOEventWorkerForeman* foreman, Action::IOEventType specialization); /** * Virtual destructor. */ ~IOEventWorker(); /** * Push list of tasks to worker. * @param tasks - &id:oatpp::async::utils::FastQueue; of &id:oatpp::async::CoroutineHandle;. */ void pushTasks(utils::FastQueue<CoroutineHandle>& tasks) override; /** * Push one task to worker. * @param task - &id:CoroutineHandle;. */ void pushOneTask(CoroutineHandle* task) override; /** * Run worker. */ void run(); /** * Break run loop. */ void stop() override; /** * Join all worker-threads. */ void join() override; /** * Detach all worker-threads. */ void detach() override; }; /** * Class responsible to assign I/O tasks to specific &l:IOEventWorker; according to worker's "specialization". <br> * Needed in order to support full-duplex I/O mode without duplicating file-descriptors. */ class IOEventWorkerForeman : public Worker { private: IOEventWorker m_reader; IOEventWorker m_writer; public: /** * Constructor. */ IOEventWorkerForeman(); /** * Virtual destructor. */ ~IOEventWorkerForeman(); /** * Push list of tasks to worker. * @param tasks - &id:oatpp::async::utils::FastQueue; of &id:oatpp::async::CoroutineHandle;. */ void pushTasks(utils::FastQueue<CoroutineHandle>& tasks) override; /** * Push one task to worker. * @param task - &id:CoroutineHandle;. */ void pushOneTask(CoroutineHandle* task) override; /** * Break run loop. */ void stop() override; /** * Join all worker-threads. */ void join() override; /** * Detach all worker-threads. */ void detach() override; }; }}} #endif //oatpp_async_worker_IOEventWorker_hpp
vincent-in-black-sesame/oat
src/oatpp/core/async/worker/IOEventWorker.hpp
C++
apache-2.0
4,933
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "IOEventWorker.hpp" #if defined(WIN32) || defined(_WIN32) #include <io.h> #else #include <unistd.h> #endif namespace oatpp { namespace async { namespace worker { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // IOEventWorker IOEventWorker::IOEventWorker(IOEventWorkerForeman* foreman, Action::IOEventType specialization) : Worker(Type::IO) , m_foreman(foreman) , m_specialization(specialization) , m_running(true) , m_eventQueueHandle(INVALID_IO_HANDLE) , m_wakeupTrigger(INVALID_IO_HANDLE) , m_inEvents(nullptr) , m_inEventsCount(0) , m_inEventsCapacity(0) , m_outEvents(nullptr) { m_thread = std::thread(&IOEventWorker::run, this); } IOEventWorker::~IOEventWorker() { #if !defined(WIN32) && !defined(_WIN32) if(m_eventQueueHandle >=0) { ::close(m_eventQueueHandle); } if(m_wakeupTrigger >= 0) { ::close(m_wakeupTrigger); } #endif } void IOEventWorker::pushTasks(utils::FastQueue<CoroutineHandle> &tasks) { if (tasks.first != nullptr) { { std::lock_guard<oatpp::concurrency::SpinLock> guard(m_backlogLock); utils::FastQueue<CoroutineHandle>::moveAll(tasks, m_backlog); } triggerWakeup(); } } void IOEventWorker::pushOneTask(CoroutineHandle *task) { { std::lock_guard<oatpp::concurrency::SpinLock> guard(m_backlogLock); m_backlog.pushBack(task); } triggerWakeup(); } void IOEventWorker::run() { initEventQueue(); while (m_running) { consumeBacklog(); waitEvents(); } } void IOEventWorker::stop() { { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_backlogLock); m_running = false; } triggerWakeup(); } void IOEventWorker::join() { m_thread.join(); } void IOEventWorker::detach() { m_thread.detach(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // IOEventWorkerForeman IOEventWorkerForeman::IOEventWorkerForeman() : Worker(Type::IO) , m_reader(this, Action::IOEventType::IO_EVENT_READ) , m_writer(this, Action::IOEventType::IO_EVENT_WRITE) {} IOEventWorkerForeman::~IOEventWorkerForeman() { } void IOEventWorkerForeman::pushTasks(utils::FastQueue<CoroutineHandle>& tasks) { utils::FastQueue<CoroutineHandle> readerTasks; utils::FastQueue<CoroutineHandle> writerTasks; while(tasks.first != nullptr) { CoroutineHandle* coroutine = tasks.popFront(); auto& action = getCoroutineScheduledAction(coroutine); switch(action.getIOEventType()) { case Action::IOEventType::IO_EVENT_READ: readerTasks.pushBack(coroutine); break; case Action::IOEventType::IO_EVENT_WRITE: writerTasks.pushBack(coroutine); break; default: throw std::runtime_error("[oatpp::async::worker::IOEventWorkerForeman::pushTasks()]: Error. Unknown Action Event Type."); } } if(readerTasks.first != nullptr) { m_reader.pushTasks(readerTasks); } if(writerTasks.first != nullptr) { m_writer.pushTasks(writerTasks); } } void IOEventWorkerForeman::pushOneTask(CoroutineHandle* task) { auto& action = getCoroutineScheduledAction(task); switch(action.getIOEventType()) { case Action::IOEventType::IO_EVENT_READ: m_reader.pushOneTask(task); break; case Action::IOEventType::IO_EVENT_WRITE: m_writer.pushOneTask(task); break; default: throw std::runtime_error("[oatpp::async::worker::IOEventWorkerForeman::pushTasks()]: Error. Unknown Action Event Type."); } } void IOEventWorkerForeman::stop() { m_writer.stop(); m_reader.stop(); } void IOEventWorkerForeman::join() { m_reader.join(); m_writer.join(); } void IOEventWorkerForeman::detach() { m_reader.detach(); m_writer.detach(); } }}}
vincent-in-black-sesame/oat
src/oatpp/core/async/worker/IOEventWorker_common.cpp
C++
apache-2.0
4,822
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "IOEventWorker.hpp" #ifdef OATPP_IO_EVENT_INTERFACE_EPOLL //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // epoll based implementation #include "oatpp/core/async/Processor.hpp" #include <unistd.h> #include <sys/epoll.h> #include <sys/eventfd.h> namespace oatpp { namespace async { namespace worker { void IOEventWorker::initEventQueue() { #if !defined __ANDROID_API__ || __ANDROID_API__ >= 21 m_eventQueueHandle = ::epoll_create1(0); #else m_eventQueueHandle = ::epoll_create(0); #endif if(m_eventQueueHandle == -1) { OATPP_LOGE("[oatpp::async::worker::IOEventWorker::initEventQueue()]", "Error. Call to ::epoll_create1() failed. errno=%d", errno); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::initEventQueue()]: Error. Call to ::epoll_create1() failed."); } m_outEvents = std::unique_ptr<v_char8[]>(new (std::nothrow) v_char8[MAX_EVENTS * sizeof(struct epoll_event)]); if(!m_outEvents) { OATPP_LOGE("[oatpp::async::worker::IOEventWorker::initEventQueue()]", "Error. Unable to allocate %d bytes for events.", MAX_EVENTS * sizeof(struct epoll_event)); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::initEventQueue()]: Error. Unable to allocate memory for events."); } m_wakeupTrigger = ::eventfd(0, EFD_NONBLOCK); if(m_wakeupTrigger == -1) { OATPP_LOGE("[oatpp::async::worker::IOEventWorker::initEventQueue()]", "Error. Call to ::eventfd() failed. errno=%d", errno); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::initEventQueue()]: Error. Call to ::eventfd() failed."); } struct epoll_event event; std::memset(&event, 0, sizeof(struct epoll_event)); event.data.ptr = this; #ifdef EPOLLEXCLUSIVE event.events = EPOLLIN | EPOLLET | EPOLLEXCLUSIVE; #else event.events = EPOLLIN | EPOLLET; #endif auto res = ::epoll_ctl(m_eventQueueHandle, EPOLL_CTL_ADD, m_wakeupTrigger, &event); if(res == -1) { OATPP_LOGE("[oatpp::async::worker::IOEventWorker::initEventQueue()]", "Error. Call to ::epoll_ctl failed. errno=%d", errno); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::initEventQueue()]: Error. Call to ::epoll_ctl() failed."); } } void IOEventWorker::triggerWakeup() { eventfd_write(m_wakeupTrigger, 1); } void IOEventWorker::setTriggerEvent(p_char8 eventPtr) { (void) eventPtr; // DO NOTHING } void IOEventWorker::setCoroutineEvent(CoroutineHandle* coroutine, int operation, p_char8 eventPtr) { (void) eventPtr; auto& action = getCoroutineScheduledAction(coroutine); switch(action.getType()) { case Action::TYPE_IO_WAIT: break; case Action::TYPE_IO_REPEAT: break; default: OATPP_LOGE("[oatpp::async::worker::IOEventWorker::pushCoroutineToQueue()]", "Error. Unknown Action. action.getType()==%d", action.getType()); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::pushCoroutineToQueue()]: Error. Unknown Action."); } struct epoll_event event; std::memset(&event, 0, sizeof(struct epoll_event)); event.data.ptr = coroutine; switch(action.getIOEventType()) { case Action::IOEventType::IO_EVENT_READ: event.events = EPOLLIN | EPOLLET | EPOLLONESHOT; break; case Action::IOEventType::IO_EVENT_WRITE: event.events = EPOLLOUT | EPOLLET | EPOLLONESHOT; break; default: throw std::runtime_error("[oatpp::async::worker::IOEventWorker::pushCoroutineToQueue()]: Error. Unknown Action Event Type."); } auto res = epoll_ctl(m_eventQueueHandle, operation, action.getIOHandle(), &event); if(res == -1) { OATPP_LOGE("[oatpp::async::worker::IOEventWorker::setEpollEvent()]", "Error. Call to epoll_ctl failed. operation=%d, errno=%d", operation, errno); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::setEpollEvent()]: Error. Call to epoll_ctl failed."); } } void IOEventWorker::consumeBacklog() { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_backlogLock); auto curr = m_backlog.first; while(curr != nullptr) { setCoroutineEvent(curr, EPOLL_CTL_ADD, nullptr); curr = nextCoroutine(curr); } m_backlog.first = nullptr; m_backlog.last = nullptr; m_backlog.count = 0; } void IOEventWorker::waitEvents() { struct epoll_event* outEvents = (struct epoll_event*)m_outEvents.get(); auto eventsCount = epoll_wait(m_eventQueueHandle, outEvents, MAX_EVENTS, -1); if((eventsCount < 0) && (errno != EINTR)) { OATPP_LOGE("[oatpp::async::worker::IOEventWorker::waitEvents()]", "Error:\n" "errno=%d\n" "in-events=%d\n" "foreman=%d\n" "this=%d\n" "specialization=%d", errno, m_inEventsCount, m_foreman, this, m_specialization); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::waitEvents()]: Error. Event loop failed."); } utils::FastQueue<CoroutineHandle> popQueue; for(v_int32 i = 0; i < eventsCount; i ++) { void* dataPtr = outEvents[i].data.ptr; if(dataPtr != nullptr) { if(dataPtr == this) { eventfd_t value; eventfd_read(m_wakeupTrigger, &value); } else { auto coroutine = (CoroutineHandle*) dataPtr; Action action = coroutine->iterate(); int res; switch(action.getIOEventCode() | m_specialization) { case Action::CODE_IO_WAIT_READ: setCoroutineScheduledAction(coroutine, std::move(action)); setCoroutineEvent(coroutine, EPOLL_CTL_MOD, nullptr); break; case Action::CODE_IO_WAIT_WRITE: setCoroutineScheduledAction(coroutine, std::move(action)); setCoroutineEvent(coroutine, EPOLL_CTL_MOD, nullptr); break; case Action::CODE_IO_REPEAT_READ: setCoroutineScheduledAction(coroutine, std::move(action)); setCoroutineEvent(coroutine, EPOLL_CTL_MOD, nullptr); break; case Action::CODE_IO_REPEAT_WRITE: setCoroutineScheduledAction(coroutine, std::move(action)); setCoroutineEvent(coroutine, EPOLL_CTL_MOD, nullptr); break; case Action::CODE_IO_WAIT_RESCHEDULE: res = epoll_ctl(m_eventQueueHandle, EPOLL_CTL_DEL, action.getIOHandle(), nullptr); if(res == -1) { OATPP_LOGE( "[oatpp::async::worker::IOEventWorker::waitEvents()]", "Error. Call to epoll_ctl failed. operation=%d, errno=%d. action_code=%d, worker_specialization=%d", EPOLL_CTL_DEL, errno, action.getIOEventCode(), m_specialization ); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::waitEvents()]: Error. Call to epoll_ctl failed."); } setCoroutineScheduledAction(coroutine, std::move(action)); popQueue.pushBack(coroutine); break; case Action::CODE_IO_REPEAT_RESCHEDULE: res = epoll_ctl(m_eventQueueHandle, EPOLL_CTL_DEL, action.getIOHandle(), nullptr); if(res == -1) { OATPP_LOGE( "[oatpp::async::worker::IOEventWorker::waitEvents()]", "Error. Call to epoll_ctl failed. operation=%d, errno=%d. action_code=%d, worker_specialization=%d", EPOLL_CTL_DEL, errno, action.getIOEventCode(), m_specialization ); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::waitEvents()]: Error. Call to epoll_ctl failed."); } setCoroutineScheduledAction(coroutine, std::move(action)); popQueue.pushBack(coroutine); break; default: auto& prevAction = getCoroutineScheduledAction(coroutine); res = epoll_ctl(m_eventQueueHandle, EPOLL_CTL_DEL, prevAction.getIOHandle(), nullptr); if(res == -1) { OATPP_LOGE("[oatpp::async::worker::IOEventWorker::waitEvents()]", "Error. Call to epoll_ctl failed. operation=%d, errno=%d", EPOLL_CTL_DEL, errno); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::waitEvents()]: Error. Call to epoll_ctl failed."); } setCoroutineScheduledAction(coroutine, std::move(action)); getCoroutineProcessor(coroutine)->pushOneTask(coroutine); } } } } if(popQueue.count > 0) { m_foreman->pushTasks(popQueue); } } }}} #endif // #ifdef OATPP_IO_EVENT_INTERFACE_EPOLL
vincent-in-black-sesame/oat
src/oatpp/core/async/worker/IOEventWorker_epoll.cpp
C++
apache-2.0
9,565
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "IOEventWorker.hpp" #ifdef OATPP_IO_EVENT_INTERFACE_KQUEUE //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // kqueue based implementation #include "oatpp/core/async/Processor.hpp" #include <sys/event.h> namespace oatpp { namespace async { namespace worker { void IOEventWorker::initEventQueue() { m_eventQueueHandle = ::kqueue(); if(m_eventQueueHandle == -1) { throw std::runtime_error("[oatpp::async::worker::IOEventWorker::initEventQueue()]: Error. Call to ::kqueue() failed."); } m_outEvents = std::unique_ptr<v_char8[]>(new (std::nothrow) v_char8[MAX_EVENTS * sizeof(struct kevent)]); if(!m_outEvents) { OATPP_LOGE("[oatpp::async::worker::IOEventWorker::initEventQueue()]", "Error. Unable to allocate %d bytes for events.", MAX_EVENTS * sizeof(struct kevent)); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::initEventQueue()]: Error. Unable to allocate memory for events."); } } void IOEventWorker::triggerWakeup() { struct kevent event; memset(&event, 0, sizeof(event)); event.ident = 0; event.filter = EVFILT_USER; event.fflags = NOTE_TRIGGER; auto res = kevent(m_eventQueueHandle, &event, 1, nullptr, 0, NULL); if(res < 0) { throw std::runtime_error("[oatpp::async::worker::IOEventWorker::triggerWakeup()]: Error. trigger wakeup failed."); } } void IOEventWorker::setTriggerEvent(p_char8 eventPtr) { struct kevent* event = (struct kevent*) eventPtr; std::memset(event, 0, sizeof(struct kevent)); event->ident = 0; event->filter = EVFILT_USER; event->flags = EV_ADD | EV_CLEAR; } void IOEventWorker::setCoroutineEvent(CoroutineHandle* coroutine, int operation, p_char8 eventPtr) { (void)operation; auto& action = getCoroutineScheduledAction(coroutine); switch(action.getType()) { case Action::TYPE_IO_WAIT: break; case Action::TYPE_IO_REPEAT: break; default: throw std::runtime_error("[oatpp::async::worker::IOEventWorker::pushCoroutineToQueue()]: Error. Unknown Action."); } struct kevent* event = (struct kevent*) eventPtr; std::memset(event, 0, sizeof(struct kevent)); event->ident = action.getIOHandle(); event->flags = EV_ADD | EV_ONESHOT; event->udata = coroutine; switch(action.getIOEventType()) { case Action::IOEventType::IO_EVENT_READ: event->filter = EVFILT_READ; break; case Action::IOEventType::IO_EVENT_WRITE: event->filter = EVFILT_WRITE; break; default: throw std::runtime_error("[oatpp::async::worker::IOEventWorker::pushCoroutineToQueue()]: Error. Unknown Action Event Type."); } } void IOEventWorker::consumeBacklog() { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_backlogLock); m_inEventsCount = m_backlog.count + 1; if(m_inEventsCapacity < m_inEventsCount) { m_inEventsCapacity = m_inEventsCount; m_inEvents = std::unique_ptr<v_char8[]>(new (std::nothrow) v_char8[m_inEventsCapacity * sizeof(struct kevent)]); if(!m_inEvents) { OATPP_LOGE("[oatpp::async::worker::IOEventWorker::consumeBacklog()]", "Error. Unable to allocate %d bytes for events.", m_inEventsCapacity * sizeof(struct kevent)); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::consumeBacklog()]: Error. Unable to allocate memory for events."); } } setTriggerEvent(&m_inEvents[0]); auto curr = m_backlog.first; v_int32 i = 1; while(curr != nullptr) { setCoroutineEvent(curr, 0, &m_inEvents[i * sizeof(struct kevent)]); curr = nextCoroutine(curr); ++i; } m_backlog.first = nullptr; m_backlog.last = nullptr; m_backlog.count = 0; } void IOEventWorker::waitEvents() { auto eventsCount = kevent(m_eventQueueHandle, (struct kevent*)m_inEvents.get(), m_inEventsCount, (struct kevent*)m_outEvents.get(), MAX_EVENTS, NULL); if((eventsCount < 0) && (errno != EINTR)) { OATPP_LOGE("[oatpp::async::worker::IOEventWorker::waitEvents()]", "Error:\n" "errno=%d\n" "in-events=%d\n" "foreman=%d\n" "this=%d\n" "specialization=%d", errno, m_inEventsCount, m_foreman, this, m_specialization); throw std::runtime_error("[oatpp::async::worker::IOEventWorker::waitEvents()]: Error. Event loop failed."); } utils::FastQueue<CoroutineHandle> repeatQueue; utils::FastQueue<CoroutineHandle> popQueue; for(v_int32 i = 0; i < eventsCount; i ++) { struct kevent* event = (struct kevent *)&m_outEvents[i * sizeof(struct kevent)]; auto coroutine = (CoroutineHandle*) event->udata; if((event->flags & EV_ERROR) > 0) { OATPP_LOGD("Error", "data='%s'", strerror((int)event->data)); continue; } if(coroutine != nullptr) { Action action = coroutine->iterate(); switch(action.getIOEventCode() | m_specialization) { case Action::CODE_IO_WAIT_READ: setCoroutineScheduledAction(coroutine, std::move(action)); repeatQueue.pushBack(coroutine); break; case Action::CODE_IO_WAIT_WRITE: setCoroutineScheduledAction(coroutine, std::move(action)); repeatQueue.pushBack(coroutine); break; case Action::CODE_IO_REPEAT_READ: setCoroutineScheduledAction(coroutine, std::move(action)); repeatQueue.pushBack(coroutine); break; case Action::CODE_IO_REPEAT_WRITE: setCoroutineScheduledAction(coroutine, std::move(action)); repeatQueue.pushBack(coroutine); break; case Action::CODE_IO_WAIT_RESCHEDULE: setCoroutineScheduledAction(coroutine, std::move(action)); popQueue.pushBack(coroutine); break; case Action::CODE_IO_REPEAT_RESCHEDULE: setCoroutineScheduledAction(coroutine, std::move(action)); popQueue.pushBack(coroutine); break; default: setCoroutineScheduledAction(coroutine, std::move(action)); getCoroutineProcessor(coroutine)->pushOneTask(coroutine); } } } if(repeatQueue.count > 0) { { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_backlogLock); utils::FastQueue<CoroutineHandle>::moveAll(repeatQueue, m_backlog); } } if(popQueue.count > 0) { m_foreman->pushTasks(popQueue); } } }}} #endif // #ifdef OATPP_IO_EVENT_INTERFACE_KQUEUE
vincent-in-black-sesame/oat
src/oatpp/core/async/worker/IOEventWorker_kqueue.cpp
C++
apache-2.0
7,458
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "IOEventWorker.hpp" #ifdef OATPP_IO_EVENT_INTERFACE_STUB //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // windows based implementation #include "oatpp/core/async/Processor.hpp" namespace oatpp { namespace async { namespace worker { void IOEventWorker::initEventQueue() { throw std::runtime_error("[IOEventWorker for Target OS is NOT IMPLEMENTED! Use IOWorker instead.]"); } void IOEventWorker::triggerWakeup() { throw std::runtime_error("[IOEventWorker for Target OS is NOT IMPLEMENTED! Use IOWorker instead.]"); } void IOEventWorker::setTriggerEvent(p_char8 eventPtr) { (void)eventPtr; throw std::runtime_error("[IOEventWorker for Target OS is NOT IMPLEMENTED! Use IOWorker instead.]"); } void IOEventWorker::setCoroutineEvent(CoroutineHandle* coroutine, int operation, p_char8 eventPtr) { (void)eventPtr; (void)coroutine; (void)operation; throw std::runtime_error("[IOEventWorker for Target OS is NOT IMPLEMENTED! Use IOWorker instead.]"); } void IOEventWorker::consumeBacklog() { throw std::runtime_error("[IOEventWorker for Target OS is NOT IMPLEMENTED! Use IOWorker instead.]"); } void IOEventWorker::waitEvents() { throw std::runtime_error("[IOEventWorker for Target OS is NOT IMPLEMENTED! Use IOWorker instead.]"); } }}} #endif // #ifdef OATPP_IO_EVENT_INTERFACE_STUB
vincent-in-black-sesame/oat
src/oatpp/core/async/worker/IOEventWorker_stub.cpp
C++
apache-2.0
2,387
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "IOWorker.hpp" #include "oatpp/core/async/Processor.hpp" #include <chrono> namespace oatpp { namespace async { namespace worker { IOWorker::IOWorker() : Worker(Type::IO) , m_running(true) { m_thread = std::thread(&IOWorker::run, this); } void IOWorker::pushTasks(utils::FastQueue<CoroutineHandle>& tasks) { { std::lock_guard<oatpp::concurrency::SpinLock> guard(m_backlogLock); utils::FastQueue<CoroutineHandle>::moveAll(tasks, m_backlog); } m_backlogCondition.notify_one(); } void IOWorker::pushOneTask(CoroutineHandle* task) { { std::lock_guard<oatpp::concurrency::SpinLock> guard(m_backlogLock); m_backlog.pushBack(task); } m_backlogCondition.notify_one(); } void IOWorker::consumeBacklog(bool blockToConsume) { if(blockToConsume) { std::unique_lock<oatpp::concurrency::SpinLock> lock(m_backlogLock); while (m_backlog.first == nullptr && m_running) { m_backlogCondition.wait(lock); } utils::FastQueue<CoroutineHandle>::moveAll(m_backlog, m_queue); } else { std::unique_lock<oatpp::concurrency::SpinLock> lock(m_backlogLock, std::try_to_lock); if (lock.owns_lock()) { utils::FastQueue<CoroutineHandle>::moveAll(m_backlog, m_queue); } } } void IOWorker::run() { v_int32 consumeIteration = 0; v_int32 roundIteration = 0; v_int64 tick =std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); while(m_running) { auto CP = m_queue.first; if(CP != nullptr) { Action action = CP->iterate(); auto& schA = getCoroutineScheduledAction(CP); switch(action.getType()) { case Action::TYPE_IO_REPEAT: dismissAction(schA); ++ roundIteration; if(roundIteration == 10) { roundIteration = 0; m_queue.round(); } break; // case Action::TYPE_IO_WAIT: // roundIteration = 0; // m_queue.round(); // break; // case Action::TYPE_IO_WAIT: // schedule for timer // roundIteration = 0; // m_queue.popFront(); // setCoroutineScheduledAction(CP, oatpp::async::Action::createWaitRepeatAction(0)); // getCoroutineProcessor(CP)->pushOneTask(CP); // break; case Action::TYPE_IO_WAIT: roundIteration = 0; if(schA.getType() == Action::TYPE_WAIT_REPEAT) { if(schA.getTimePointMicroseconds() < tick) { m_queue.popFront(); setCoroutineScheduledAction(CP, oatpp::async::Action::createWaitRepeatAction(0)); getCoroutineProcessor(CP)->pushOneTask(CP); } else { m_queue.round(); } } else { setCoroutineScheduledAction(CP, oatpp::async::Action::createWaitRepeatAction(tick + 1000000)); m_queue.round(); } break; default: roundIteration = 0; m_queue.popFront(); setCoroutineScheduledAction(CP, std::move(action)); getCoroutineProcessor(CP)->pushOneTask(CP); break; } ++ consumeIteration; if(consumeIteration == 100) { consumeIteration = 0; consumeBacklog(false); std::chrono::microseconds ms = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()); tick = ms.count(); } } else { consumeBacklog(true); std::chrono::microseconds ms = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()); tick = ms.count(); } } } void IOWorker::stop() { { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_backlogLock); m_running = false; } m_backlogCondition.notify_one(); } void IOWorker::join() { m_thread.join(); } void IOWorker::detach() { m_thread.detach(); } }}}
vincent-in-black-sesame/oat
src/oatpp/core/async/worker/IOWorker.cpp
C++
apache-2.0
4,951
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_async_worker_IOWorker_hpp #define oatpp_async_worker_IOWorker_hpp #include "./Worker.hpp" #include "oatpp/core/concurrency/SpinLock.hpp" #include <thread> #include <mutex> #include <condition_variable> namespace oatpp { namespace async { namespace worker { /** * Naive implementation of IOWorker. * Polls all I/O handles in a loop. Reschedules long-waiting handles to Timer. */ class IOWorker : public Worker { private: bool m_running; utils::FastQueue<CoroutineHandle> m_backlog; utils::FastQueue<CoroutineHandle> m_queue; oatpp::concurrency::SpinLock m_backlogLock; std::condition_variable_any m_backlogCondition; private: std::thread m_thread; private: void consumeBacklog(bool blockToConsume); public: /** * Constructor. */ IOWorker(); /** * Push list of tasks to worker. * @param tasks - &id:oatpp::async::utils::FastQueue; of &id:oatpp::async::CoroutineHandle;. */ void pushTasks(utils::FastQueue<CoroutineHandle>& tasks) override; /** * Push one task to worker. * @param task - &id:CoroutineHandle;. */ void pushOneTask(CoroutineHandle* task) override; /** * Run worker. */ void run(); /** * Break run loop. */ void stop() override; /** * Join all worker-threads. */ void join() override; /** * Detach all worker-threads. */ void detach() override; }; }}} #endif //oatpp_async_worker_IOWorker_hpp
vincent-in-black-sesame/oat
src/oatpp/core/async/worker/IOWorker.hpp
C++
apache-2.0
2,402
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "TimerWorker.hpp" #include "oatpp/core/async/Processor.hpp" #include <chrono> namespace oatpp { namespace async { namespace worker { TimerWorker::TimerWorker(const std::chrono::duration<v_int64, std::micro>& granularity) : Worker(Type::TIMER) , m_running(true) , m_granularity(granularity) { m_thread = std::thread(&TimerWorker::run, this); } void TimerWorker::pushTasks(utils::FastQueue<CoroutineHandle>& tasks) { { std::lock_guard<oatpp::concurrency::SpinLock> guard(m_backlogLock); utils::FastQueue<CoroutineHandle>::moveAll(tasks, m_backlog); } m_backlogCondition.notify_one(); } void TimerWorker::consumeBacklog() { std::unique_lock<oatpp::concurrency::SpinLock> lock(m_backlogLock); while (m_backlog.first == nullptr && m_queue.first == nullptr && m_running) { m_backlogCondition.wait(lock); } utils::FastQueue<CoroutineHandle>::moveAll(m_backlog, m_queue); } void TimerWorker::pushOneTask(CoroutineHandle* task) { { std::lock_guard<oatpp::concurrency::SpinLock> guard(m_backlogLock); m_backlog.pushBack(task); } m_backlogCondition.notify_one(); } void TimerWorker::run() { while(m_running) { consumeBacklog(); auto curr = m_queue.first; CoroutineHandle* prev = nullptr; auto startTime = std::chrono::system_clock::now(); std::chrono::microseconds ms = std::chrono::duration_cast<std::chrono::microseconds>(startTime.time_since_epoch()); v_int64 tick = ms.count(); while(curr != nullptr) { auto next = nextCoroutine(curr); const Action& schA = getCoroutineScheduledAction(curr); if(schA.getTimePointMicroseconds() < tick) { Action action = curr->iterate(); switch(action.getType()) { case Action::TYPE_WAIT_REPEAT: setCoroutineScheduledAction(curr, std::move(action)); break; case Action::TYPE_IO_WAIT: setCoroutineScheduledAction(curr, oatpp::async::Action::createWaitRepeatAction(0)); break; default: m_queue.cutEntry(curr, prev); setCoroutineScheduledAction(curr, std::move(action)); getCoroutineProcessor(curr)->pushOneTask(curr); curr = prev; break; } } prev = curr; curr = next; } auto elapsed = std::chrono::system_clock::now() - startTime; if(elapsed < m_granularity) { std::this_thread::sleep_for(m_granularity - elapsed); } } } void TimerWorker::stop() { { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_backlogLock); m_running = false; } m_backlogCondition.notify_one(); } void TimerWorker::join() { m_thread.join(); } void TimerWorker::detach() { m_thread.detach(); } }}}
vincent-in-black-sesame/oat
src/oatpp/core/async/worker/TimerWorker.cpp
C++
apache-2.0
3,750
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_async_worker_TimerWorker_hpp #define oatpp_async_worker_TimerWorker_hpp #include "./Worker.hpp" #include "oatpp/core/concurrency/SpinLock.hpp" #include <thread> #include <mutex> #include <condition_variable> namespace oatpp { namespace async { namespace worker { /** * Timer worker. * Used to wait for timer-scheduled coroutines. */ class TimerWorker : public Worker { private: std::atomic<bool> m_running; utils::FastQueue<CoroutineHandle> m_backlog; utils::FastQueue<CoroutineHandle> m_queue; oatpp::concurrency::SpinLock m_backlogLock; std::condition_variable_any m_backlogCondition; private: std::chrono::duration<v_int64, std::micro> m_granularity; private: std::thread m_thread; private: void consumeBacklog(); public: /** * Constructor. * @param granularity - minimum possible time to wait. */ TimerWorker(const std::chrono::duration<v_int64, std::micro>& granularity = std::chrono::milliseconds(100)); /** * Push list of tasks to worker. * @param tasks - &id:oatpp::aysnc::utils::FastQueue; of &id:oatpp::async::CoroutineHandle;. */ void pushTasks(utils::FastQueue<CoroutineHandle>& tasks) override; /** * Push one task to worker. * @param task - &id:CoroutineHandle;. */ void pushOneTask(CoroutineHandle* task) override; /** * Run worker. */ void run(); /** * Break run loop. */ void stop() override; /** * Join all worker-threads. */ void join() override; /** * Detach all worker-threads. */ void detach() override; }; }}} #endif //oatpp_async_worker_TimerWorker_hpp
vincent-in-black-sesame/oat
src/oatpp/core/async/worker/TimerWorker.hpp
C++
apache-2.0
2,599
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Worker.hpp" namespace oatpp { namespace async { namespace worker { Worker::Worker(Type type) : m_type(type) {} void Worker::setCoroutineScheduledAction(CoroutineHandle* coroutine, Action &&action) { coroutine->_SCH_A = std::forward<Action>(action); } Action& Worker::getCoroutineScheduledAction(CoroutineHandle* coroutine) { return coroutine->_SCH_A; } Processor* Worker::getCoroutineProcessor(CoroutineHandle* coroutine) { return coroutine->_PP; } void Worker::dismissAction(Action& action) { action.m_type = Action::TYPE_NONE; } CoroutineHandle* Worker::nextCoroutine(CoroutineHandle* coroutine) { return coroutine->_ref; } Worker::Type Worker::getType() { return m_type; } }}}
vincent-in-black-sesame/oat
src/oatpp/core/async/worker/Worker.cpp
C++
apache-2.0
1,708
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_async_worker_Worker_hpp #define oatpp_async_worker_Worker_hpp #include "oatpp/core/async/Coroutine.hpp" #include <thread> namespace oatpp { namespace async { namespace worker { /** * Worker base class. * Workers are used by &id:oatpp::async::Executor; to reschedule worker-specific tasks from &id:oatpp::async::Processor;. */ class Worker { public: /** * Worker type */ enum Type : v_int32 { /** * Worker type - general processor. */ PROCESSOR = 0, /** * Worker type - timer processor. */ TIMER = 1, /** * Worker type - I/O processor. */ IO = 2, /** * Number of types in this enum. */ TYPES_COUNT = 3 }; private: Type m_type; protected: static void setCoroutineScheduledAction(CoroutineHandle* coroutine, Action&& action); static Action& getCoroutineScheduledAction(CoroutineHandle* coroutine); static Processor* getCoroutineProcessor(CoroutineHandle* coroutine); static void dismissAction(Action& action); static CoroutineHandle* nextCoroutine(CoroutineHandle* coroutine); public: /** * Constructor. * @param type - worker type - one of &l:Worker::Type; values. */ Worker(Type type); /** * Default virtual destructor. */ virtual ~Worker() = default; /** * Push list of tasks to worker. * @param tasks - &id:oatpp::async::utils::FastQueue; of &id:oatpp::async::CoroutineHandle;. */ virtual void pushTasks(utils::FastQueue<CoroutineHandle>& tasks) = 0; /** * Push one task to worker. * @param task - &id:oatpp::async::CoroutineHandle;. */ virtual void pushOneTask(CoroutineHandle* task) = 0; /** * Break run loop. */ virtual void stop() = 0; /** * Join all worker-threads. */ virtual void join() = 0; /** * Detach all worker-threads. */ virtual void detach() = 0; /** * Get worker type. * @return - one of &l:Worker::Type; values. */ Type getType(); }; }}} #endif //oatpp_async_worker_Worker_hpp
vincent-in-black-sesame/oat
src/oatpp/core/async/worker/Worker.hpp
C++
apache-2.0
3,017
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "CommandLineArguments.hpp" #include <cstring> namespace oatpp { namespace base { CommandLineArguments::CommandLineArguments() : m_argc(0) , m_argv(nullptr) {} CommandLineArguments::CommandLineArguments(int argc, const char * argv[]) : m_argc(argc) , m_argv(argv) {} bool CommandLineArguments::Parser::hasArgument(int argc, const char * argv[], const char* argName) { return getArgumentIndex(argc, argv, argName) >= 0; } v_int32 CommandLineArguments::Parser::getArgumentIndex(int argc, const char * argv[], const char* argName) { for(v_int32 i = 0; i < argc; i ++) { if(std::strcmp(argName, argv[i]) == 0){ return i; } } return -1; } const char* CommandLineArguments::Parser::getArgumentStartingWith(int argc, const char * argv[], const char* argNamePrefix, const char* defaultValue) { for(v_int32 i = 0; i < argc; i ++) { if(std::strncmp(argNamePrefix, argv[i], std::strlen(argNamePrefix)) == 0){ return argv[i]; } } return defaultValue; } const char* CommandLineArguments::Parser::getNamedArgumentValue(int argc, const char * argv[], const char* argName, const char* defaultValue) { for(v_int32 i = 0; i < argc; i ++) { if(std::strcmp(argName, argv[i]) == 0){ if(i + 1 < argc) { return argv[i + 1]; } } } return defaultValue; } }}
vincent-in-black-sesame/oat
src/oatpp/core/base/CommandLineArguments.cpp
C++
apache-2.0
2,334
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_base_CommandLineArguments_hpp #define oatpp_base_CommandLineArguments_hpp #include "./Environment.hpp" namespace oatpp { namespace base { /** * Class for storing and managing Command Line arguments. */ class CommandLineArguments { public: /** * Command Line arguments parser. */ class Parser { public: /** * Check the specified argument is present among command line arguments. * @param argc - count of arguments in argv array. * @param argv - array of arguments. * @param argName - name of the target argument. * @return - `true` if `getArgumentIndex(argName) >= 0` */ static bool hasArgument(int argc, const char * argv[], const char* argName); /** * get index of the argument with the name == argName */ /** * Get index of the argument specified by name in the argv[] array. * @param argc - count of arguments in argv array. * @param argv - array of arguments. * @param argName - name of the target argument. * @return - index of the argument in argv[] array. -1 if there is no such argument. */ static v_int32 getArgumentIndex(int argc, const char * argv[], const char* argName); /** * Get argument which starts with the prefix. <br> * Example: <br> * For command line: `-k -c 1000 -n 100 http://127.0.0.1:8000/` <br> * `getArgumentWhichStartsWith("http") == http://127.0.0.1:8000/` * @param argc - count of arguments in argv array. * @param argv - array of arguments. * @param argNamePrefix - prefix to search. * @param defaultValue - default value to return in case not found. * @return - argument which starts with the specified prefix. */ static const char* getArgumentStartingWith(int argc, const char * argv[], const char* argNamePrefix, const char* defaultValue = nullptr); /** * Get value preceded by the argument. <br> * Example: <br> * For command line: `-k -c 1000 -n 100` <br> * `getNamedArgumentValue("-c") == "1000"`, `getNamedArgumentValue("-n") == "100"` * @param argc - count of arguments in argv array. * @param argv - array of arguments. * @param argName - name of the preceded argument. * @param defaultValue - default value to return in case not found. * @return - value preceded by the argument. */ static const char* getNamedArgumentValue(int argc, const char * argv[], const char* argName, const char* defaultValue = nullptr); }; private: int m_argc; const char ** m_argv; public: /** * Default constructor. */ CommandLineArguments(); /** * Constructor. * @param argc - count of arguments in argv[] array. * @param argv - array of arguments. */ CommandLineArguments(int argc, const char * argv[]); /** * Check the specified argument is present. * @param argName - name of the target argument. * @return - `true` if present. */ bool hasArgument(const char* argName) const { return Parser::hasArgument(m_argc, m_argv, argName); } /** * Get index of the argument specified by name. * @param argName - name of the target argument. * @return - index of the argument in argv[] array. -1 if there is no such argument. */ v_int32 getArgumentIndex(const char* argName) const { return Parser::getArgumentIndex(m_argc, m_argv, argName); } /** * Get argument which starts with the prefix. <br> * Example: <br> * For command line: `-k -c 1000 -n 100 'http://127.0.0.1:8000/'` <br> * `getArgumentWhichStartsWith("http") == http://127.0.0.1:8000/` * @param argNamePrefix - prefix to search. * @param defaultValue - default value to return in case not found. * @return - argument which starts with the specified prefix. defaultValue if not found. */ const char* getArgumentStartingWith(const char* argNamePrefix, const char* defaultValue = nullptr) const { return Parser::getArgumentStartingWith(m_argc, m_argv, argNamePrefix, defaultValue); } /** * Get value preceded by the argument. <br> * Example: <br> * For command line: `-k -c 1000 -n 100` <br> * `getNamedArgumentValue("-c") == "1000"`, `getNamedArgumentValue("-n") == "100"` * @param argName - name of the preceded argument. * @param defaultValue - default value to return in case not found. * @return - value preceded by the argument. defaultValue if not found. */ const char* getNamedArgumentValue(const char* argName, const char* defaultValue = nullptr) const { return Parser::getNamedArgumentValue(m_argc, m_argv, argName, defaultValue); } }; }} #endif /* oatpp_base_CommandLineArguments_hpp */
vincent-in-black-sesame/oat
src/oatpp/core/base/CommandLineArguments.hpp
C++
apache-2.0
5,678
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /** * This is list of default configuration params and values which you can * configure in the build-time */ #ifndef oatpp_base_Config_hpp #define oatpp_base_Config_hpp /** * If NOT DISABLED, counting of all object of class oatpp::base::Countable is enabled * for debug purposes and detection of memory leaks. * Disable object counting for Release builds using '-D OATPP_DISABLE_ENV_OBJECT_COUNTERS' flag for better performance */ //#define OATPP_DISABLE_ENV_OBJECT_COUNTERS /** * Define this to disable memory-pool allocations. * This will make oatpp::base::memory::MemoryPool, method obtain and free call new and delete directly */ //#define OATPP_DISABLE_POOL_ALLOCATIONS /** * Predefined value for function oatpp::concurrency::Thread::getHardwareConcurrency(); */ //#define OATPP_THREAD_HARDWARE_CONCURRENCY 4 /** * Number of shards of ThreadDistributedMemoryPool (Default pool for many oatpp objects) * Higher number reduces threads racing for resources on each shard. */ #ifndef OATPP_THREAD_DISTRIBUTED_MEM_POOL_SHARDS_COUNT #define OATPP_THREAD_DISTRIBUTED_MEM_POOL_SHARDS_COUNT 10 #endif /** * Disable `thread_local` feature. <br> * See https://github.com/oatpp/oatpp/issues/81 */ //#define OATPP_COMPAT_BUILD_NO_THREAD_LOCAL 1 #ifndef OATPP_FLOAT_STRING_FORMAT #define OATPP_FLOAT_STRING_FORMAT "%.16g" #endif /** * DISABLE logs priority V */ //#define OATPP_DISABLE_LOGV /** * DISABLE logs priority D */ //#define OATPP_DISABLE_LOGD /** * DISABLE logs priority I */ //#define OATPP_DISABLE_LOGI /** * DISABLE logs priority W */ //#define OATPP_DISABLE_LOGW /** * DISABLE logs priority E */ //#define OATPP_DISABLE_LOGE #endif /* oatpp_base_Config_hpp */
vincent-in-black-sesame/oat
src/oatpp/core/base/Config.hpp
C++
apache-2.0
2,707
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Countable.hpp" namespace oatpp { namespace base{ Countable::Countable() { #ifndef OATPP_DISABLE_ENV_OBJECT_COUNTERS Environment::incObjects(); #endif } Countable::Countable(const Countable& other) { (void)other; #ifndef OATPP_DISABLE_ENV_OBJECT_COUNTERS Environment::incObjects(); #endif } Countable::~Countable(){ #ifndef OATPP_DISABLE_ENV_OBJECT_COUNTERS Environment::decObjects(); #endif } }}
vincent-in-black-sesame/oat
src/oatpp/core/base/Countable.cpp
C++
apache-2.0
1,419
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_base_Countable #define oatpp_base_Countable #include <memory> #include "./Environment.hpp" namespace oatpp { namespace base{ /** * Class instantiations of which can be counted. */ class Countable { public: /** * Constructor. Increment counter calling &id:oatpp::base::Environment::incObjects;. */ Countable(); /** * Copy constructor. Increment counter calling &id:oatpp::base::Environment::incObjects;. * @param other */ Countable(const Countable& other); /** * Virtual destructor. Decrement counter calling &id:oatpp::base::Environment::decObjects;. */ virtual ~Countable(); Countable& operator = (Countable&) = default; }; }} #endif /* oatpp_base_Countable */
vincent-in-black-sesame/oat
src/oatpp/core/base/Countable.hpp
C++
apache-2.0
1,721
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <oatpp@bamkrs.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Environment.hpp" #include <iomanip> #include <chrono> #include <iostream> #include <cstring> #include <ctime> #include <cstdarg> #if defined(WIN32) || defined(_WIN32) #include <WinSock2.h> struct tm* localtime_r(time_t *_clock, struct tm *_result) { localtime_s(_result, _clock); return _result; } #endif namespace oatpp { namespace base { v_atomicCounter Environment::m_objectsCount(0); v_atomicCounter Environment::m_objectsCreated(0); #ifndef OATPP_COMPAT_BUILD_NO_THREAD_LOCAL thread_local v_counter Environment::m_threadLocalObjectsCount = 0; thread_local v_counter Environment::m_threadLocalObjectsCreated = 0; #endif std::mutex& Environment::getComponentsMutex() { static std::mutex componentsMutex; return componentsMutex; } std::unordered_map<std::string, std::unordered_map<std::string, void*>>& Environment::getComponents() { static std::unordered_map<std::string, std::unordered_map<std::string, void*>> components; return components; } std::shared_ptr<Logger> Environment::m_logger; DefaultLogger::DefaultLogger(const Config& config) : m_config(config) {} void DefaultLogger::log(v_uint32 priority, const std::string& tag, const std::string& message) { bool indent = false; auto time = std::chrono::system_clock::now().time_since_epoch(); std::lock_guard<std::mutex> lock(m_lock); switch (priority) { case PRIORITY_V: std::cout << "\033[0m V \033[0m|"; break; case PRIORITY_D: std::cout << "\033[34m D \033[0m|"; break; case PRIORITY_I: std::cout << "\033[32m I \033[0m|"; break; case PRIORITY_W: std::cout << "\033[45m W \033[0m|"; break; case PRIORITY_E: std::cout << "\033[41m E \033[0m|"; break; default: std::cout << " " << priority << " |"; } if (m_config.timeFormat) { time_t seconds = std::chrono::duration_cast<std::chrono::seconds>(time).count(); struct tm now; localtime_r(&seconds, &now); #ifdef OATPP_DISABLE_STD_PUT_TIME char timeBuffer[50]; strftime(timeBuffer, sizeof(timeBuffer), m_config.timeFormat, &now); std::cout << timeBuffer; #else std::cout << std::put_time(&now, m_config.timeFormat); #endif indent = true; } if (m_config.printTicks) { auto ticks = std::chrono::duration_cast<std::chrono::microseconds>(time).count(); if(indent) { std::cout << " "; } std::cout << ticks; indent = true; } if (indent) { std::cout << "|"; } if (message.empty()) { std::cout << " " << tag << std::endl; } else { std::cout << " " << tag << ":" << message << std::endl; } } void DefaultLogger::enablePriority(v_uint32 priority) { if (priority > PRIORITY_E) { return; } m_config.logMask |= (1 << priority); } void DefaultLogger::disablePriority(v_uint32 priority) { if (priority > PRIORITY_E) { return; } m_config.logMask &= ~(1 << priority); } bool DefaultLogger::isLogPriorityEnabled(v_uint32 priority) { if (priority > PRIORITY_E) { return true; } return m_config.logMask & (1 << priority); } void LogCategory::enablePriority(v_uint32 priority) { if (priority > Logger::PRIORITY_E) { return; } enabledPriorities |= (1 << priority); } void LogCategory::disablePriority(v_uint32 priority) { if (priority > Logger::PRIORITY_E) { return; } enabledPriorities &= ~(1 << priority); } bool LogCategory::isLogPriorityEnabled(v_uint32 priority) { if (priority > Logger::PRIORITY_E) { return true; } return enabledPriorities & (1 << priority); } void Environment::init() { init(std::make_shared<DefaultLogger>()); } void Environment::init(const std::shared_ptr<Logger>& logger) { m_logger = logger; #if defined(WIN32) || defined(_WIN32) // Initialize Winsock WSADATA wsaData; int iResult; iResult = WSAStartup(MAKEWORD(2,2), &wsaData); if (iResult != 0) { throw std::runtime_error("[oatpp::base::Environment::init()]: Error. WSAStartup failed"); } #endif checkTypes(); m_objectsCount = 0; m_objectsCreated = 0; #ifndef OATPP_COMPAT_BUILD_NO_THREAD_LOCAL m_threadLocalObjectsCount = 0; m_threadLocalObjectsCreated = 0; #endif { std::lock_guard<std::mutex> lock(getComponentsMutex()); if (getComponents().size() > 0) { throw std::runtime_error("[oatpp::base::Environment::init()]: Error. " "Invalid state. Components were created before call to Environment::init()"); } } } void Environment::destroy(){ if(getComponents().size() > 0) { std::lock_guard<std::mutex> lock(getComponentsMutex()); throw std::runtime_error("[oatpp::base::Environment::destroy()]: Error. " "Invalid state. Leaking components"); } m_logger.reset(); #if defined(WIN32) || defined(_WIN32) WSACleanup(); #endif } void Environment::checkTypes(){ static_assert(sizeof(v_char8) == 1, ""); static_assert(sizeof(v_int16) == 2, ""); static_assert(sizeof(v_uint16) == 2, ""); static_assert(sizeof(v_int32) == 4, ""); static_assert(sizeof(v_int64) == 8, ""); static_assert(sizeof(v_uint32) == 4, ""); static_assert(sizeof(v_uint64) == 8, ""); static_assert(sizeof(v_float64) == 8, ""); v_int32 vInt32 = ~v_int32(1); v_int64 vInt64 = ~v_int64(1); v_uint32 vUInt32 = ~v_uint32(1); v_uint64 vUInt64 = ~v_uint64(1); OATPP_ASSERT(vInt32 < 0); OATPP_ASSERT(vInt64 < 0); OATPP_ASSERT(vUInt32 > 0); OATPP_ASSERT(vUInt64 > 0); } void Environment::incObjects(){ m_objectsCount ++; m_objectsCreated ++; #ifndef OATPP_COMPAT_BUILD_NO_THREAD_LOCAL m_threadLocalObjectsCount ++; m_threadLocalObjectsCreated ++; #endif } void Environment::decObjects(){ m_objectsCount --; #ifndef OATPP_COMPAT_BUILD_NO_THREAD_LOCAL m_threadLocalObjectsCount --; #endif } v_counter Environment::getObjectsCount(){ return m_objectsCount; } v_counter Environment::getObjectsCreated(){ return m_objectsCreated; } v_counter Environment::getThreadLocalObjectsCount(){ #ifndef OATPP_COMPAT_BUILD_NO_THREAD_LOCAL return m_threadLocalObjectsCount; #else return 0; #endif } v_counter Environment::getThreadLocalObjectsCreated(){ #ifndef OATPP_COMPAT_BUILD_NO_THREAD_LOCAL return m_threadLocalObjectsCreated; #else return 0; #endif } void Environment::setLogger(const std::shared_ptr<Logger>& logger){ m_logger = logger; } std::shared_ptr<Logger> Environment::getLogger() { return m_logger; } void Environment::printCompilationConfig() { OATPP_LOGD("oatpp-version", OATPP_VERSION); #ifdef OATPP_DISABLE_ENV_OBJECT_COUNTERS OATPP_LOGD("oatpp/Config", "OATPP_DISABLE_ENV_OBJECT_COUNTERS"); #endif #ifdef OATPP_COMPAT_BUILD_NO_THREAD_LOCAL OATPP_LOGD("oatpp/Config", "OATPP_COMPAT_BUILD_NO_THREAD_LOCAL"); #endif #ifdef OATPP_THREAD_HARDWARE_CONCURRENCY OATPP_LOGD("oatpp/Config", "OATPP_THREAD_HARDWARE_CONCURRENCY=%d", OATPP_THREAD_HARDWARE_CONCURRENCY); #endif } void Environment::log(v_uint32 priority, const std::string& tag, const std::string& message) { if(m_logger != nullptr) { m_logger->log(priority, tag, message); } } void Environment::logFormatted(v_uint32 priority, const LogCategory& category, const char* message, ...) { if (category.categoryEnabled && (category.enabledPriorities & (1 << priority))) { va_list args; va_start(args, message); vlogFormatted(priority, category.tag, message, args); va_end(args); } } void Environment::logFormatted(v_uint32 priority, const std::string& tag, const char* message, ...) { va_list args; va_start(args, message); vlogFormatted(priority, tag, message, args); va_end(args); } void Environment::vlogFormatted(v_uint32 priority, const std::string& tag, const char* message, va_list args) { // do we have a logger and the priority is enabled? if (m_logger == nullptr || !m_logger->isLogPriorityEnabled(priority)) { return; } // if we dont need to format anything, just print the message if(message == nullptr) { log(priority, tag, std::string()); return; } // check how big our buffer has to be va_list argscpy; va_copy(argscpy, args); v_buff_size allocsize = vsnprintf(nullptr, 0, message, argscpy) + 1; // alloc the buffer (or the max size) if (allocsize > m_logger->getMaxFormattingBufferSize()) { allocsize = m_logger->getMaxFormattingBufferSize(); } auto buffer = std::unique_ptr<char[]>(new char[allocsize]); memset(buffer.get(), 0, allocsize); // actually format vsnprintf(buffer.get(), allocsize, message, args); // call (user) providen log function log(priority, tag, buffer.get()); } void Environment::registerComponent(const std::string& typeName, const std::string& componentName, void* component) { std::lock_guard<std::mutex> lock(getComponentsMutex()); auto& bucket = getComponents()[typeName]; auto it = bucket.find(componentName); if(it != bucket.end()){ throw std::runtime_error("[oatpp::base::Environment::registerComponent()]: Error. Component with given name already exists: name='" + componentName + "'"); } bucket[componentName] = component; } void Environment::unregisterComponent(const std::string& typeName, const std::string& componentName) { std::lock_guard<std::mutex> lock(getComponentsMutex()); auto& components = getComponents(); auto bucketIt = getComponents().find(typeName); if(bucketIt == components.end() || bucketIt->second.size() == 0) { throw std::runtime_error("[oatpp::base::Environment::unregisterComponent()]: Error. Component of given type doesn't exist: type='" + typeName + "'"); } auto& bucket = bucketIt->second; auto componentIt = bucket.find(componentName); if(componentIt == bucket.end()) { throw std::runtime_error("[oatpp::base::Environment::unregisterComponent()]: Error. Component with given name doesn't exist: name='" + componentName + "'"); } bucket.erase(componentIt); if(bucket.size() == 0) { components.erase(bucketIt); } } void* Environment::getComponent(const std::string& typeName) { std::lock_guard<std::mutex> lock(getComponentsMutex()); auto& components = getComponents(); auto bucketIt = components.find(typeName); if(bucketIt == components.end() || bucketIt->second.size() == 0) { throw std::runtime_error("[oatpp::base::Environment::getComponent()]: Error. Component of given type doesn't exist: type='" + typeName + "'"); } auto bucket = bucketIt->second; if(bucket.size() > 1){ throw std::runtime_error("[oatpp::base::Environment::getComponent()]: Error. Ambiguous component reference. Multiple components exist for a given type: type='" + typeName + "'"); } return bucket.begin()->second; } void* Environment::getComponent(const std::string& typeName, const std::string& componentName) { std::lock_guard<std::mutex> lock(getComponentsMutex()); auto& components = getComponents(); auto bucketIt = components.find(typeName); if(bucketIt == components.end() || bucketIt->second.size() == 0) { throw std::runtime_error("[oatpp::base::Environment::getComponent()]: Error. Component of given type doesn't exist: type='" + typeName + "'"); } auto bucket = bucketIt->second; auto componentIt = bucket.find(componentName); if(componentIt == bucket.end()) { throw std::runtime_error("[oatpp::base::Environment::getComponent()]: Error. Component with given name doesn't exist: name='" + componentName + "'"); } return componentIt->second; } v_int64 Environment::getMicroTickCount(){ std::chrono::microseconds ms = std::chrono::duration_cast<std::chrono::microseconds> (std::chrono::system_clock::now().time_since_epoch()); return ms.count(); } }}
vincent-in-black-sesame/oat
src/oatpp/core/base/Environment.cpp
C++
apache-2.0
12,744
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <oatpp@bamkrs.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_base_Environment_hpp #define oatpp_base_Environment_hpp #include "./Config.hpp" #include <cstdio> #include <atomic> #include <mutex> #include <string> #include <unordered_map> #include <memory> #include <stdexcept> #include <cstdlib> #define OATPP_VERSION "1.3.0" typedef unsigned char v_char8; typedef v_char8 *p_char8; typedef int8_t v_int8; typedef v_int8* p_int8; typedef uint8_t v_uint8; typedef v_uint8* p_uint8; typedef int16_t v_int16; typedef v_int16* p_int16; typedef uint16_t v_uint16; typedef v_uint16* p_uint16; typedef int32_t v_int32; typedef v_int32* p_int32; typedef uint32_t v_uint32; typedef v_uint32* p_uint32; typedef int64_t v_int64; typedef v_int64* p_int64; typedef uint64_t v_uint64; typedef v_uint64* p_uint64; typedef double v_float64; typedef v_float64 * p_float64; typedef float v_float32; typedef v_float32* p_float32; typedef std::atomic_int_fast64_t v_atomicCounter; typedef v_int64 v_counter; /** * This type is the integer type capable of storing a pointer. Thus is capable of storing size of allocated memory. <br> * Use this type to define a size for the buffer. */ typedef intptr_t v_buff_size; typedef v_buff_size* p_buff_size; typedef uintptr_t v_buff_usize; typedef v_buff_usize* p_buff_usize; namespace oatpp { namespace base { /** * Interface for system-wide Logger.<br> * All calls to `OATPP_DISABLE_LOGV`, `OATPP_DISABLE_LOGD`, `OATPP_DISABLE_LOGI`, * `OATPP_DISABLE_LOGW`, `OATPP_DISABLE_LOGE` will come here. */ class Logger { public: /** * Log priority V-verbouse. */ static constexpr v_uint32 PRIORITY_V = 0; /** * Log priority D-debug. */ static constexpr v_uint32 PRIORITY_D = 1; /** * Log priority I-Info. */ static constexpr v_uint32 PRIORITY_I = 2; /** * Log priority W-Warning. */ static constexpr v_uint32 PRIORITY_W = 3; /** * Log priority E-error. */ static constexpr v_uint32 PRIORITY_E = 4; public: /** * Virtual Destructor. */ virtual ~Logger() = default; /** * Log message with priority, tag, message. * @param priority - priority channel of the message. * @param tag - tag of the log message. * @param message - message. */ virtual void log(v_uint32 priority, const std::string& tag, const std::string& message) = 0; /** * Returns wether or not a priority should be logged/printed * @param priority * @return - true if given priority should be logged */ virtual bool isLogPriorityEnabled(v_uint32 ) { return true; } /** * Should return the maximum amount of bytes that should be allocated for a single log message * @return - maximum buffer size */ virtual v_buff_size getMaxFormattingBufferSize() { return 4096; } }; /** * Describes a logging category (i.e. a logging "namespace") */ class LogCategory { public: /** * Constructs a logging category. * @param pTag - Tag of this logging category * @param pCategoryEnabled - Enable or disable the category completely * @param pEnabledPriorities - Bitmap of initially active logging categories. */ LogCategory(std::string pTag, bool pCategoryEnabled, v_uint32 pEnabledPriorities = ((1<<Logger::PRIORITY_V) | (1<<Logger::PRIORITY_D) | (1<<Logger::PRIORITY_I) | (1<<Logger::PRIORITY_W) | (1<<Logger::PRIORITY_E))) : tag(std::move(pTag)) , categoryEnabled(pCategoryEnabled) , enabledPriorities(pEnabledPriorities) {}; /** * The tag for this category */ const std::string tag; /** * Generally enable or disable this category */ bool categoryEnabled; /** * Priorities to print that are logged in this category */ v_uint32 enabledPriorities; /** * Enables logging of a priorities for this category * @param priority - the priority level to enable */ void enablePriority(v_uint32 priority); /** * Disabled logging of a priorities for this category * @param priority - the priority level to disable */ void disablePriority(v_uint32 priority); /** * Returns wether or not a priority of this category should be logged/printed * @param priority * @return - true if given priority should be logged */ bool isLogPriorityEnabled(v_uint32 priority); }; /** * Default Logger implementation. */ class DefaultLogger : public Logger { public: /** * Default Logger Config. */ struct Config { /** * Constructor. * @param tfmt - time format. * @param printMicroTicks - show ticks in microseconds. */ Config(const char* tfmt, bool printMicroTicks, v_uint32 initialLogMask) : timeFormat(tfmt) , printTicks(printMicroTicks) , logMask(initialLogMask) {} /** * Time format of the log message. * If nullptr then do not print time. */ const char* timeFormat; /** * Print micro-ticks in the log message. */ bool printTicks; /** * Log mask to enable/disable certain priorities */ v_uint32 logMask; }; private: Config m_config; std::mutex m_lock; public: /** * Constructor. * @param config - Logger config. */ DefaultLogger(const Config& config = Config( "%Y-%m-%d %H:%M:%S", true, (1 << PRIORITY_V) | (1 << PRIORITY_D) | (1 << PRIORITY_I) | (1 << PRIORITY_W) | (1 << PRIORITY_E) )); /** * Log message with priority, tag, message. * @param priority - log-priority channel of the message. * @param tag - tag of the log message. * @param message - message. */ void log(v_uint32 priority, const std::string& tag, const std::string& message) override; /** * Enables logging of a priorities for this instance * @param priority - the priority level to enable */ void enablePriority(v_uint32 priority); /** * Disables logging of a priority for this instance * @param priority - the priority level to disable */ void disablePriority(v_uint32 priority); /** * Returns wether or not a priority should be logged/printed * @param priority * @return - true if given priority should be logged */ bool isLogPriorityEnabled(v_uint32 priority) override; }; /** * Class to manage application environment.<br> * Manage object counters, manage components, and do system health-checks. */ class Environment{ private: static v_atomicCounter m_objectsCount; static v_atomicCounter m_objectsCreated; #ifndef OATPP_COMPAT_BUILD_NO_THREAD_LOCAL static thread_local v_counter m_threadLocalObjectsCount; static thread_local v_counter m_threadLocalObjectsCreated; #endif private: static std::mutex& getComponentsMutex(); static std::unordered_map<std::string, std::unordered_map<std::string, void*>>& getComponents(); private: static std::shared_ptr<Logger> m_logger; static void checkTypes(); public: /** * Class representing system component. * @tparam T - component type. */ template <typename T> class Component { private: std::string m_type; std::string m_name; T m_object; public: /** * Constructor. * @param name - component name. * @param object - component object. */ Component(const std::string& name, const T& object) : m_type(typeid(T).name()) , m_name(name) , m_object(object) { Environment::registerComponent(m_type, m_name, &m_object); } /** * Constructor. * @param object - component object. */ Component(const T& object) : Component("NoName", object) {} /** * Non-virtual Destructor. */ ~Component() { Environment::unregisterComponent(m_type, m_name); } /** * Get object stored in the component. * @return - object. */ T getObject() { return m_object; } }; private: static void registerComponent(const std::string& typeName, const std::string& componentName, void* component); static void unregisterComponent(const std::string& typeName, const std::string& componentName); static void vlogFormatted(v_uint32 priority, const std::string& tag, const char* message, va_list args); public: /** * Initialize environment and do basic health-checks. */ static void init(); /** * Initialize environment and do basic health-checks. * @param logger - system-wide logger. */ static void init(const std::shared_ptr<Logger>& logger); /** * De-initialize environment and do basic health-checks. * Check for memory leaks. */ static void destroy(); /** * increment counter of objects. */ static void incObjects(); /** * decrement counter of objects. */ static void decObjects(); /** * Get count of objects currently allocated and stored in the memory. * @return */ static v_counter getObjectsCount(); /** * Get count of objects created for a whole system lifetime. * @return - count of objects. */ static v_counter getObjectsCreated(); /** * Same as `getObjectsCount()` but `thread_local` * @return - count of objects. <br> * *0 - if built with `-DOATPP_COMPAT_BUILD_NO_THREAD_LOCAL` flag* */ static v_counter getThreadLocalObjectsCount(); /** * Same as `getObjectsCreated()` but `thread_local` * @return - count of objects. <br> * *0 - if built with `-DOATPP_COMPAT_BUILD_NO_THREAD_LOCAL` flag* */ static v_counter getThreadLocalObjectsCreated(); /** * Set environment logger. * @param logger - system-wide logger. */ static void setLogger(const std::shared_ptr<Logger>& logger); /** * Gets the current environment logger * @return - current logger */ static std::shared_ptr<Logger> getLogger(); /** * Print debug information of compilation config.<br> * Print values for: <br> * - `OATPP_DISABLE_ENV_OBJECT_COUNTERS`<br> * - `OATPP_THREAD_HARDWARE_CONCURRENCY`<br> */ static void printCompilationConfig(); /** * Call `Logger::log()` * @param priority - log-priority channel of the message. * @param tag - tag of the log message. * @param message - message. */ static void log(v_uint32 priority, const std::string& tag, const std::string& message); /** * Format message and call `Logger::log()`<br> * Message is formatted using `vsnprintf` method. * @param priority - log-priority channel of the message. * @param tag - tag of the log message. * @param message - message. * @param ... - format arguments. */ static void logFormatted(v_uint32 priority, const std::string& tag, const char* message, ...); /** * Format message and call `Logger::log()`<br> * Message is formatted using `vsnprintf` method. * @param priority - log-priority channel of the message. * @param category - category of the log message. * @param message - message. * @param ... - format arguments. */ static void logFormatted(v_uint32 priority, const LogCategory& category, const char* message, ...); /** * Get component object by typeName. * @param typeName - type name of the component. * @return - pointer to a component object. */ static void* getComponent(const std::string& typeName); /** * Get component object by typeName and componentName. * @param typeName - type name of the component. * @param componentName - component qualifier name. * @return - pointer to a component object. */ static void* getComponent(const std::string& typeName, const std::string& componentName); /** * Get ticks count in microseconds. * @return - ticks count in microseconds. */ static v_int64 getMicroTickCount(); }; /** * Default oatpp assert method. * @param EXP - expression that must be `true`. */ #define OATPP_ASSERT(EXP) \ if(!(EXP)) { \ OATPP_LOGE("\033[1mASSERT\033[0m[\033[1;31mFAILED\033[0m]", #EXP); \ exit(EXIT_FAILURE); \ } /** * Convenience macro to declare a logging category directly in a class header. * @param NAME - variable-name of the category which is later used to reference the category. */ #define OATPP_DECLARE_LOG_CATEGORY(NAME) \ static oatpp::base::LogCategory NAME; /** * Convenience macro to implement a logging category directly in a class header. * @param NAME - variable-name of the category which is later used to reference the category. * @param TAG - tag printed with each message printed usig this category. * @param ENABLED - enable or disable a category (bool). */ #define OATPP_LOG_CATEGORY(NAME, TAG, ENABLED) \ oatpp::base::LogCategory NAME = oatpp::base::LogCategory(TAG, ENABLED); #ifndef OATPP_DISABLE_LOGV /** * Log message with &l:Logger::PRIORITY_V; <br> * *To disable this log compile oatpp with `#define OATPP_DISABLE_LOGV`* * @param TAG - message tag. * @param ...(1) - message. * @param ... - optional format parameter. */ #define OATPP_LOGV(TAG, ...) \ oatpp::base::Environment::logFormatted(oatpp::base::Logger::PRIORITY_V, TAG, __VA_ARGS__); #else #define OATPP_LOGV(TAG, ...) #endif #ifndef OATPP_DISABLE_LOGD /** * Log message with &l:Logger::PRIORITY_D; <br> * *To disable this log compile oatpp with `#define OATPP_DISABLE_LOGD`* * @param TAG - message tag. * @param ...(1) - message. * @param ... - optional format parameter. */ #define OATPP_LOGD(TAG, ...) \ oatpp::base::Environment::logFormatted(oatpp::base::Logger::PRIORITY_D, TAG, __VA_ARGS__); #else #define OATPP_LOGD(TAG, ...) #endif #ifndef OATPP_DISABLE_LOGI /** * Log message with &l:Logger::PRIORITY_I; <br> * *To disable this log compile oatpp with `#define OATPP_DISABLE_LOGI`* * @param TAG - message tag. * @param ...(1) - message. * @param ... - optional format parameter. */ #define OATPP_LOGI(TAG, ...) \ oatpp::base::Environment::logFormatted(oatpp::base::Logger::PRIORITY_I, TAG, __VA_ARGS__); #else #define OATPP_LOGI(TAG, ...) #endif #ifndef OATPP_DISABLE_LOGW /** * Log message with &l:Logger::PRIORITY_W; <br> * *To disable this log compile oatpp with `#define OATPP_DISABLE_LOGW`* * @param TAG - message tag. * @param ...(1) - message. * @param ... - optional format parameter. */ #define OATPP_LOGW(TAG, ...) \ oatpp::base::Environment::logFormatted(oatpp::base::Logger::PRIORITY_W, TAG, __VA_ARGS__); #else #define OATPP_LOGW(TAG, ...) #endif #ifndef OATPP_DISABLE_LOGE /** * Log message with &l:Logger::PRIORITY_E; <br> * *To disable this log compile oatpp with `#define OATPP_DISABLE_LOGE`* * @param TAG - message tag. * @param ...(1) - message. * @param ... - optional format parameter. */ #define OATPP_LOGE(TAG, ...) \ oatpp::base::Environment::logFormatted(oatpp::base::Logger::PRIORITY_E, TAG, __VA_ARGS__); #else #define OATPP_LOGE(TAG, ...) #endif }} #endif /* oatpp_base_Environment_hpp */
vincent-in-black-sesame/oat
src/oatpp/core/base/Environment.hpp
C++
apache-2.0
15,850
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_base_ObjectHandle_hpp #define oatpp_base_ObjectHandle_hpp #include "./Environment.hpp" namespace oatpp { namespace base { template<class T> class ObjectHandle { private: T* m_object; std::shared_ptr<T> m_ptr; public: ObjectHandle(T* object) : m_object(object) {} template<class Q> ObjectHandle(const std::shared_ptr<Q>& sharedObject) : m_object(sharedObject.get()) , m_ptr(sharedObject) {} std::shared_ptr<T> getPtr() const { return m_ptr; } T* get() const { return m_object; } T* operator->() const { return m_object; } explicit operator bool() const { return m_object != nullptr; } }; }} #endif //oatpp_base_ObjectHandle_hpp
vincent-in-black-sesame/oat
src/oatpp/core/base/ObjectHandle.hpp
C++
apache-2.0
1,707
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "SpinLock.hpp" #include <thread> namespace oatpp { namespace concurrency { SpinLock::SpinLock() : m_atom(false) {} void SpinLock::lock() { while (std::atomic_exchange_explicit(&m_atom, true, std::memory_order_acquire)) { std::this_thread::yield(); } } void SpinLock::unlock() { std::atomic_store_explicit(&m_atom, false, std::memory_order_release); } bool SpinLock::try_lock() { return !std::atomic_exchange_explicit(&m_atom, true, std::memory_order_acquire); } }}
vincent-in-black-sesame/oat
src/oatpp/core/concurrency/SpinLock.cpp
C++
apache-2.0
1,495