Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: POC for new sdk js lib implementation #159

Merged
merged 7 commits into from
Jun 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ target/
node_modules/
dist/
/crates/spin-js-engine/sdk.js
.spin/
.spin/
spin-sdk/lib/
3 changes: 0 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ target/release/spinjs: target/wasm32-wasi/release/spin-js-engine.wasm
cd crates/spin-js-cli && \
SPIN_JS_ENGINE_PATH=../../target/wasm32-wasi/release/spin_js_engine.wasm \
cargo build --release $(BUILD_TARGET)
echo "import \"./modules/overrides\"" >> crates/spin-js-engine/src/js_sdk/dist/sdk.d.ts
cp crates/spin-js-engine/src/js_sdk/dist/sdk.d.ts types/lib/index.d.ts
cp -r crates/spin-js-engine/src/js_sdk/dist/modules types/lib/

target/wasm32-wasi/release/spin-js-engine.wasm: crates/spin-js-engine/sdk.ts crates/spin-js-engine/src/lib.rs
cd crates/spin-js-engine && \
Expand Down
2 changes: 0 additions & 2 deletions crates/spin-js-engine/src/js_sdk/modules/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ require('fast-text-encoding')

let encoder = new TextEncoder()

/** @internal */
declare var _random: {
math_rand: () => number
get_rand: () => number
Expand All @@ -11,7 +10,6 @@ declare var _random: {
timing_safe_equals: (value1: ArrayBuffer, value2: ArrayBuffer) => boolean
}

/** @internal */
export const crypto = {
getRandomValues: function <T extends ArrayBufferView | null>(array: T) {
if (array) {
Expand Down
2 changes: 0 additions & 2 deletions crates/spin-js-engine/src/js_sdk/modules/fsPromises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ declare const _fsPromises: {
}
}

/** @internal */
const fsPromises = {
readFile: (filename: string) => {
return Promise.resolve(_fsPromises.readFile(filename))
Expand All @@ -43,5 +42,4 @@ declare global {
}
}

/** @internal */
export { fsPromises }
1 change: 0 additions & 1 deletion crates/spin-js-engine/src/js_sdk/modules/glob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ declare const _glob: {
get:(arg0: string) => Array<string>
}

/** @internal */
export function glob(globString: string) {
return _glob.get(globString)
}
2 changes: 0 additions & 2 deletions crates/spin-js-engine/src/js_sdk/modules/random.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
/** @internal */
declare var _random: {
math_rand: () => number
get_rand: () => number
}

/** @internal */
Math.random = function () {
return _random.math_rand();
}
49 changes: 4 additions & 45 deletions crates/spin-js-engine/src/js_sdk/modules/spinSdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,8 @@ require('fast-text-encoding')
let encoder = new TextEncoder()
let decoder = new TextDecoder()

/** @internal */
import { statusTextList } from "./statusTextList"

interface SpinConfig {
get(arg0: string): string
}

interface BaseHttpRequest {
method: string
uri: string
Expand All @@ -35,7 +30,6 @@ interface HttpResponse extends BaseHttpResponse {
body?: ArrayBuffer | string | Uint8Array
}

type HandleRequest = (request: HttpRequest) => Promise<HttpResponse>

type RdbmsParam = null | boolean | string | number | ArrayBuffer
interface RdmsReturn {
Expand All @@ -45,34 +39,9 @@ interface RdmsReturn {
]
}
interface SpinSDK {
config: SpinConfig
/** @internal */
http: {
send: (arg0: BaseHttpRequest) => InternalHttpResponse
}
redis: {
execute: (address: string, command: string, args: Array< ArrayBuffer | bigint>) => undefined | string | bigint | ArrayBuffer
get: (address: string, key: string) => ArrayBuffer
incr: (address: string, key: string) => bigint
publish: (address: string, channel: string, value: ArrayBuffer) => undefined
set: (address: string, key: string, value: ArrayBuffer) => undefined
del: (address: string, key: Array<string>) => bigint
sadd: (address: string, key: string, values: Array<string>) => bigint
smembers: (address: string, key: string) => Array<string>
srem: (address: string, key: string, values: Array<string>) => bigint
}
kv: {
open: (name: string) => KvStore
openDefault: () => KvStore
}
mysql: {
execute: (address: string, statement: string, params: RdbmsParam[]) => void
query: (address: string, statement: string, params: RdbmsParam[]) => RdmsReturn
}
pg: {
execute: (address: string, statement: string, params: RdbmsParam[]) => void
query: (address: string, statement: string, params: RdbmsParam[]) => RdmsReturn
}
}

interface FetchOptions {
Expand Down Expand Up @@ -112,7 +81,7 @@ function encodeBody(body: ArrayBuffer | Uint8Array | string) {
/** @internal */
function fetch(uri: string | URL, options?: FetchOptions) {
let encodedBodyData = (options && options.body) ? encodeBody(options.body) : new Uint8Array().buffer
const { status, headers, body } = spinSdk.http.send({
const { status, headers, body } = __internal__.spin_sdk.http.send({
method: (options && options.method) || "GET",
uri: (uri instanceof URL) ? uri.toString() : uri,
headers: (options && options.headers) || {},
Expand Down Expand Up @@ -201,22 +170,12 @@ const spinInternal = {
}
}

type Handler = (request: HttpRequest, response: ResponseBuilder) => Promise<void>


declare global {
const spinSdk: SpinSDK
function fetch(uri: string | URL, options?: FetchOptions): Promise<FetchResult>
interface KvStore {
delete: (key: string) => void
exists: (key: string) => boolean
get: (key: string) => ArrayBuffer | null
getKeys: () => Array<string>
set: (key: string, value: ArrayBuffer | string) => void
}
const __internal__: {
spin_sdk: SpinSDK
}
}

/** @internal */
export { fetch, spinInternal }

export { Handler, HttpRequest, HttpResponse, HandleRequest }
25 changes: 0 additions & 25 deletions crates/spin-js-engine/src/js_sdk/modules/utils.ts

This file was deleted.

14 changes: 1 addition & 13 deletions crates/spin-js-engine/src/js_sdk/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,12 @@ require('fast-text-encoding')

/** @internal */
import { fetch, spinInternal } from "./modules/spinSdk"
import { Handler, HttpRequest, HttpResponse, HandleRequest } from "./modules/spinSdk"

/** @internal */
import { fsPromises } from "./modules/fsPromises"
import "./modules/fsPromises"

/** @internal */
import { glob } from "./modules/glob"
import "./modules/glob"

/** @internal */
import { atob, btoa, Buffer } from "./modules/stringHandling"
Expand All @@ -24,15 +21,6 @@ import "./modules/random"

/** @internal */
import { URL, URLSearchParams } from "./modules/url"
import "./modules/url"

/** @internal */
import { utils } from "./modules/utils"
import "./modules/utils"


/** @internal */
export { atob, btoa, Buffer, fetch, fsPromises, glob, crypto, URL, URLSearchParams, utils, spinInternal }

// Stuff to be exported to the sdk types file
export { Handler, HttpRequest, HttpResponse, HandleRequest }
export { atob, btoa, Buffer, fetch, fsPromises, glob, crypto, URL, URLSearchParams, spinInternal }
54 changes: 29 additions & 25 deletions crates/spin-js-engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1051,33 +1051,9 @@ fn do_init() -> Result<()> {

let context = Context::default();
context.eval_global("sdk.js", include_str!("../sdk.js"))?;
context.eval_global("script.js", &script)?;

let global = context.global_object()?;

let entrypoint;
if global
.get_property("spin")?
.get_property("handler")?
.is_function()
{
// handler(req, res) signature exists
entrypoint = global
.get_property("spinInternal")?
.get_property("_handler")?;
} else if global
.get_property("spin")?
.get_property("handleRequest")?
.is_function()
{
// Fall back to handler(req) signature
entrypoint = global
.get_property("spinInternal")?
.get_property("_handleRequest")?;
} else {
panic!("expected function named \"handleRequest\" or \"handler\" in \"spin\"")
}

let console = context.object_value()?;
console.set_property("log", context.wrap_callback(console_log)?)?;

Expand Down Expand Up @@ -1142,13 +1118,41 @@ fn do_init() -> Result<()> {
context.wrap_callback(timing_safe_equals)?,
)?;

let internal_implementations = context.object_value()?;
internal_implementations.set_property("spin_sdk", spin_sdk)?;

global.set_property("_random", _random)?;
global.set_property("spinSdk", spin_sdk)?;
global.set_property("__internal__", internal_implementations)?;
global.set_property("_fsPromises", fs_promises)?;
global.set_property("_glob", _glob)?;

global.set_property("setTimeout", context.wrap_callback(set_timeout)?)?;

context.eval_global("script.js", &script)?;

let entrypoint;
if global
.get_property("spin")?
.get_property("handler")?
.is_function()
{
// handler(req, res) signature exists
entrypoint = global
.get_property("spinInternal")?
.get_property("_handler")?;
} else if global
.get_property("spin")?
.get_property("handleRequest")?
.is_function()
{
// Fall back to handler(req) signature
entrypoint = global
.get_property("spinInternal")?
.get_property("_handleRequest")?;
} else {
panic!("expected function named \"handleRequest\" or \"handler\" in \"spin\"")
}

let on_resolve = context.wrap_callback(on_resolve)?;
let on_reject = context.wrap_callback(on_reject)?;

Expand Down
2 changes: 1 addition & 1 deletion examples/javascript/sqlite/src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const encoder = new TextEncoder("utf-8");

export async function handleRequest(request) {
const conn = spinSdk.sqlite.openDefault();
const conn = __internal__.spin_sdk.sqlite.openDefault();
const result = conn.execute("SELECT * FROM todos WHERE id > (?);", [1]);

return {
Expand Down
16 changes: 16 additions & 0 deletions examples/typescript/sdk-poc-ts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
## Hello World

This is the simplest example of using the Javascript SDK.

### Building the example

```
npm run build
```
### Running the example

```
spin up --follow-all
```

Use e.g. `curl -v http://127.0.0.1:3000/hello` to test the endpoint.
Loading