1 /*
2   Licensed to the Apache Software Foundation (ASF) under one
3   or more contributor license agreements.  See the NOTICE file
4   distributed with this work for additional information
5   regarding copyright ownership.  The ASF licenses this file
6   to you under the Apache License, Version 2.0 (the
7   "License"); you may not use this file except in compliance
8   with the License.  You may obtain a copy of the License at
9 
10   http://www.apache.org/licenses/LICENSE-2.0
11 
12   Unless required by applicable law or agreed to in writing, software
13   distributed under the License is distributed on an "AS IS" BASIS,
14   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   See the License for the specific language governing permissions and
16   limitations under the License.
17 */
18 
19 #pragma once
20 
21 #include <stdio.h>
22 
23 #include "lua.h"
24 #include "lualib.h"
25 #include "lauxlib.h"
26 #include <ts/ts.h>
27 
28 struct async_item;
29 typedef int (*async_clean)(struct async_item *item);
30 
31 /* context stats */
32 typedef struct {
33   TSMutex mutexp;  // mutex for the following stats
34   int gc_kb;       // last recorded gc kbytes
35   int gc_kb_max;   // maximum recorded gc kbytes
36   int threads;     // associated coroutines
37   int threads_max; // max coroutines
38 } ts_lua_ctx_stats;
39 
40 /* main context*/
41 typedef struct {
42   lua_State *lua;          // basic lua vm, injected
43   TSMutex mutexp;          // mutex for lua vm
44   int gref;                // reference for lua vm self, in reg table
45   ts_lua_ctx_stats *stats; // per vm stats
46 } ts_lua_main_ctx;
47 
48 /* coroutine */
49 typedef struct {
50   ts_lua_main_ctx *mctx;
51   lua_State *lua; // derived lua_thread
52   int ref;        // reference for lua_thread, in REG Table
53 } ts_lua_coroutine;
54 
55 /* continuation info */
56 typedef struct {
57   ts_lua_coroutine routine;
58   TSCont contp;                   // continuation for the routine
59   TSMutex mutex;                  // mutex for continuation
60   struct async_item *async_chain; // async_item list
61 } ts_lua_cont_info;
62 
63 /* asynchronous item */
64 typedef struct async_item {
65   struct async_item *next;
66   ts_lua_cont_info *cinfo;
67 
68   TSCont contp; // continuation for the async operation
69   void *data;   // private data
70 
71   async_clean cleanup; // cleanup function
72   unsigned int deleted : 1;
73 } ts_lua_async_item;
74 
75 ts_lua_async_item *ts_lua_async_create_item(TSCont cont, async_clean func, void *d, ts_lua_cont_info *ci);
76 void ts_lua_release_cont_info(ts_lua_cont_info *ci);
77