Skip to content
Open
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
67 changes: 42 additions & 25 deletions .github/workflows/internal_release.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
name: Internal Release

# ONE internal (dev) release for both SDKs from a single `release/*` branch — no separate
# flowvault-release branch, no two PRs. What gets published is decided by the SCOPE of changes
# (relative to main), mirroring the skyflow-js internal workflow:
# common/ or a shared root changed -> publish BOTH skyvault + flowvault
# only skyvault/ changed -> publish skyvault
# only flowvault/ changed -> publish flowvault
# (Public/beta releases stay per-product via their tag namespaces — this scope logic is internal-only.)
# Internal (dev) releases. The publish target is chosen by the RELEASE BRANCH NAME, with a
# scope-based fallback on the shared `release/*` branch:
# skyvault-release/* -> publish skyvault only
# flowvault-release/* -> publish flowvault only
# release/* -> decide by the SCOPE of changes vs main (common/ or a shared root ->
# BOTH skyvault + flowvault; only skyvault/ -> skyvault; only flowvault/ -> flowvault)
# (Public/beta releases stay per-product via their tag namespaces — this logic is internal-only.)
on:
push:
tags-ignore:
Expand All @@ -15,12 +15,14 @@ on:
- "skyvault/build.gradle"
- "flowvault/build.gradle"
- "*.md"
# Sample apps are not shipped artifacts — a samples-only change must not trigger an internal
# (dev) release. (The scope step also treats samples/ as out-of-scope, so nothing would publish
# even if triggered; this stops the workflow from running at all for samples-only pushes.)
# Sample apps are not shipped artifacts — a samples-only (or docs-only) push must not trigger
# an internal (dev) release on any release branch; this stops the workflow from running at all
# for such pushes. (On release/*, the scope step also treats samples/ as out-of-scope.)
- "samples/**"
branches:
- release/*
- skyvault-release/*
- flowvault-release/*

jobs:
internal-release:
Expand All @@ -40,27 +42,42 @@ jobs:
distribution: 'temurin'
java-version: '17'

- name: Detect changed scope + base versions
- name: Detect scope (by branch) + base versions
id: scope
run: |
# Update origin/main's tracking ref explicitly, then base the merge-base on it.
# Do NOT use FETCH_HEAD here: the `git fetch --tags` below re-points FETCH_HEAD at
# the release branch, so `merge-base FETCH_HEAD HEAD` collapsed to HEAD -> empty diff
# -> both SDKs read as out-of-scope -> publish skipped.
# origin/main is needed for the base-version tags below, and for the release/* scope
# fallback. Do NOT use FETCH_HEAD: the `git fetch --tags` below re-points FETCH_HEAD at
# the release branch, which would collapse `merge-base FETCH_HEAD HEAD` to HEAD.
git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
git fetch --tags --quiet
# Diff vs where this release branch diverged from main (idempotent across re-pushes).
BASE=$(git merge-base origin/main HEAD)
CHANGED=$(git diff --name-only "$BASE" HEAD)
echo "Merge-base with main: $BASE"
echo "Changed files:"; echo "$CHANGED"

# Shared roots feed BOTH SDK builds -> treat like common.
SHARED='^(common/|scripts/|build\.gradle|settings\.gradle|gradle/|gradle\.properties|gradlew|\.github/workflows/)'
# Publish target is chosen by the release branch name; release/* falls back to change scope.
# skyvault-release/* -> skyvault only
# flowvault-release/* -> flowvault only
# release/* -> scope of changes vs main (common/ or shared root -> both)
sky=false; fv=false
if echo "$CHANGED" | grep -qE "$SHARED"; then sky=true; fv=true; fi
if echo "$CHANGED" | grep -qE '^skyvault/'; then sky=true; fi
if echo "$CHANGED" | grep -qE '^flowvault/'; then fv=true; fi
case "$GITHUB_REF_NAME" in
skyvault-release/*)
sky=true
echo "Branch '$GITHUB_REF_NAME' -> skyvault only"
;;
flowvault-release/*)
fv=true
echo "Branch '$GITHUB_REF_NAME' -> flowvault only"
;;
*)
# Diff vs where this release branch diverged from main (idempotent across re-pushes).
BASE=$(git merge-base origin/main HEAD)
CHANGED=$(git diff --name-only "$BASE" HEAD)
echo "Merge-base with main: $BASE"
echo "Changed files:"; echo "$CHANGED"
# Shared roots feed BOTH SDK builds -> treat like common.
SHARED='^(common/|scripts/|build\.gradle|settings\.gradle|gradle/|gradle\.properties|gradlew|\.github/workflows/)'
if echo "$CHANGED" | grep -qE "$SHARED"; then sky=true; fv=true; fi
if echo "$CHANGED" | grep -qE '^skyvault/'; then sky=true; fi
if echo "$CHANGED" | grep -qE '^flowvault/'; then fv=true; fi
;;
esac

# Base versions for the -dev suffix (skyvault: latest plain-semver tag on main; flowvault: latest flowvault/x.y.z).
skytag=$(git describe --tags --abbrev=0 --match '[0-9]*.[0-9]*.[0-9]*' origin/main 2>/dev/null || echo "1.27.0")
Expand Down
4 changes: 4 additions & 0 deletions common/src/main/kotlin/Skyflow/container/Container.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ class Container<T : ContainerProtocol> internal constructor(

internal val collectElements: MutableList<TextField> = mutableListOf();
internal val revealElements: MutableList<Label> = mutableListOf()
// File-upload elements. Typed as the neutral [Element] base so core stays free of the skyvault-only
// file types (FileInputElement); the skyvault `create`/`uploadFiles` extensions cast back. Only the
// skyvault SDK ever populates this.
internal val fileElements: MutableList<Element> = mutableListOf()
internal lateinit var context: Context
internal lateinit var composableLayout: LinearLayout
internal lateinit var options: ContainerOptions
Expand Down
12 changes: 11 additions & 1 deletion common/src/main/kotlin/Skyflow/core/Messages.kt
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,17 @@ enum class Messages(val message: String) {
INVALID_INPUT_TRANSLATION("invalid or unsupported translation provided for %s element type."),
EMPTY_INPUT_TRANSLATION("translation not passed. Switching to default translation %s"),

MISMATCH_ELEMENT_COUNT_LAYOUT_SUM("$SDK_NAME_VERSION Mount failed. Invalid layout array values. Make sure all values in the layout array are positive numbers.")
MISMATCH_ELEMENT_COUNT_LAYOUT_SUM("$SDK_NAME_VERSION Mount failed. Invalid layout array values. Make sure all values in the layout array are positive numbers."),

// file upload validations
NO_FILE_ELEMENTS("$SDK_NAME_VERSION File upload failed. No file elements found in the container. Create a file element before calling 'uploadFiles'."),
FILE_UPLOAD_ELEMENT_NOT_MOUNTED("$SDK_NAME_VERSION File upload failed. Make sure all file elements are mounted before calling 'uploadFiles'."),
FILE_NOT_SELECTED("$SDK_NAME_VERSION File upload failed. No file selected for '%s' column. Choose a file before calling 'uploadFiles'."),
EMPTY_FILE("$SDK_NAME_VERSION File upload failed. The selected file '%s' is empty. Choose a non-empty file."),
FILE_TYPE_NOT_ALLOWED("$SDK_NAME_VERSION File upload failed. File type of '%s' is not allowed."),
FILE_SIZE_EXCEEDED("$SDK_NAME_VERSION File upload failed. File '%s' exceeds the maximum allowed size."),
FILE_COUNT_EXCEEDED("$SDK_NAME_VERSION File upload failed. Number of files for '%s' column exceeds the maximum allowed count."),
INVALID_FILE_NAME("$SDK_NAME_VERSION File upload failed. File name '%s' is invalid. Only alphanumeric characters and !-_.*() are allowed.")
}

// Resolve the SDK-identity placeholder to the running product's version. Single-sourced so BOTH
Expand Down
42 changes: 42 additions & 0 deletions common/src/main/kotlin/Skyflow/core/file/FileUploadRequestBody.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package Skyflow.core.file

import android.content.ContentResolver
import android.net.Uri
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okio.BufferedSink
import okio.source
import java.io.IOException

/**
* An OkHttp [RequestBody] that streams a file straight from its `content://` [uri] via
* [ContentResolver]. It never reads the whole file into memory (4 × 32 MB would OOM the app) and
* never copies it to disk — the bytes go from the provider's input stream to the socket.
*
* Internal to `common/` and contract-agnostic, so both SDKs' upload paths share it.
*/
internal class FileUploadRequestBody(
private val contentResolver: ContentResolver,
private val uri: Uri,
mimeType: String?,
private val declaredLength: Long = -1L,
) : RequestBody() {

private val mediaType: MediaType? =
(mimeType ?: "application/octet-stream").toMediaTypeOrNull()

override fun contentType(): MediaType? = mediaType

override fun contentLength(): Long = declaredLength

override fun writeTo(sink: BufferedSink) {
// Don't put the content:// Uri in the message: it can embed the document id / file name, and
// this text is surfaced back to the host in the error response.
val input = contentResolver.openInputStream(uri)
?: throw IOException("Unable to open input stream for the selected file.")
input.use { stream ->
sink.writeAll(stream.source())
}
}
}
161 changes: 161 additions & 0 deletions common/src/main/kotlin/Skyflow/core/file/FileUploadValidator.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
package Skyflow.core.file

/**
* Client-side file validation shared by both SDKs. Pure and contract-agnostic: it works on
* primitives + [SelectedFile] (no skyvault/flowvault types), so it lives in `common/` and can be
* reused when flowvault adopts file upload.
*
* [validate] returns a [FileValidationError] (or `null` when the selection is valid) rather than
* throwing — the element shows its [FileValidationError.displayMessage] as soon as files are picked,
* and `uploadFiles(...)` reports its [FileValidationError.reportMessage]. The order of checks matches
* the other native SDK so both surface the same error for the same selection. The server enforces
* these rules too; this is the first, friendlier line of defence.
*/
internal object FileUploadValidator {

/**
* Server-fixed cap for a single [Skyflow.FileElementType.FILE_INPUT], and the default per-file
* cap for a multi-file element. 32 MB decimal (32_000_000 bytes).
*/
const val SINGLE_FILE_MAX_BYTES: Long = 32_000_000L

/** Default max files for a multi-file element when `maxFileCount` is not set. */
const val DEFAULT_MAX_FILE_COUNT: Int = 4

// Dangerous/unsupported types, blocked regardless of allowedFileType (.apk is Android-specific).
private val BLOCKED_EXTENSIONS = setOf("zip", "exe", "rar", "deb", "apk")

// File-name character rule: alphanumerics and ! - _ . * ( ). [isValidFileName] rejects a name
// with any other character on the preserveFileName path; [sanitizeFileName] replaces them with '_'.
private val UNSAFE_NAME_CHARS = Regex("[^A-Za-z0-9!\\-_.*()]")

/**
* Clean a file name for upload: trim it and replace every character outside the allowed set with
* `_`, keeping the dot(s) and extension; a blank name falls back to `file`. Applied on the
* `preserveFileName = true` upload path as a final trim/safeguard — invalid names are already
* rejected up front by [isValidFileName].
*/
fun sanitizeFileName(name: String): String {
val trimmed = name.trim()
if (trimmed.isEmpty()) return "file"
return trimmed.replace(UNSAFE_NAME_CHARS, "_")
}

/**
* Whether [name] is a valid upload name when `preserveFileName` is on: non-empty after trimming
* and containing only alphanumerics and ! - _ . * ( ).
*/
fun isValidFileName(name: String): Boolean {
val trimmed = name.trim()
return trimmed.isNotEmpty() && !UNSAFE_NAME_CHARS.containsMatchIn(trimmed)
}

/**
* Validate one element's current selection. Returns the first [FileValidationError], or `null`
* when every file passes.
*
* @param isMultiple a multi-file element (honours [maxFileCount]); single otherwise.
* @param required at least one file must be selected.
* @param maxFileSizeBytes effective per-file cap in bytes.
* @param maxFileCount effective max file count (1 for a single element).
* @param preserveFileName when on, the original name is uploaded and so is validated.
*/
fun validate(
files: List<SelectedFile>,
isMultiple: Boolean,
required: Boolean,
allowedFileType: Array<String>?,
blockEmptyFiles: Boolean,
preserveFileName: Boolean,
maxFileSizeBytes: Long,
maxFileCount: Int,
): FileValidationError? {
if (files.isEmpty()) {
return if (required) FileValidationError.NoFileSelected else null
}
return if (isMultiple)
validateMultiple(files, allowedFileType, blockEmptyFiles, preserveFileName, maxFileSizeBytes, maxFileCount)
else
validateSingle(files[0], allowedFileType, blockEmptyFiles, preserveFileName, maxFileSizeBytes)
}

private fun validateSingle(
file: SelectedFile,
allowedFileType: Array<String>?,
blockEmptyFiles: Boolean,
preserveFileName: Boolean,
maxFileSizeBytes: Long,
): FileValidationError? {
contentError(file, allowedFileType, blockEmptyFiles)?.let { return it }
if (file.sizeBytes > maxFileSizeBytes) return FileValidationError.InvalidFileSize
return nameError(file, preserveFileName)
}

private fun validateMultiple(
files: List<SelectedFile>,
allowedFileType: Array<String>?,
blockEmptyFiles: Boolean,
preserveFileName: Boolean,
maxFileSizeBytes: Long,
maxFileCount: Int,
): FileValidationError? {
val countExceeded = files.size > maxFileCount
val oversized = files.filter { it.sizeBytes > maxFileSizeBytes }
if (countExceeded) {
return if (oversized.isEmpty())
FileValidationError.FileCountExceeded(maxFileCount)
else
FileValidationError.FileCountAndSizeExceeded(maxFileCount, maxFileSizeBytes)
}
if (oversized.isNotEmpty()) {
return FileValidationError.FileSizeExceeded(maxFileSizeBytes, oversized.map { it.name })
}
for (file in files) {
(contentError(file, allowedFileType, blockEmptyFiles) ?: nameError(file, preserveFileName))
?.let { return it }
}
return null
}

/** Type (blocked list + allowedFileType) and emptiness. */
private fun contentError(
file: SelectedFile,
allowedFileType: Array<String>?,
blockEmptyFiles: Boolean,
): FileValidationError? {
if (BLOCKED_EXTENSIONS.contains(file.extension)) return FileValidationError.InvalidFileType
if (!allowedFileType.isNullOrEmpty() && !matchesAllowedType(file, allowedFileType)) {
return FileValidationError.InvalidFileType
}
if (blockEmptyFiles && file.sizeBytes == 0L) return FileValidationError.InvalidFileSize
return null
}

/** Original name is uploaded when [preserveFileName] is on, so reject a name outside the set. */
private fun nameError(file: SelectedFile, preserveFileName: Boolean): FileValidationError? {
if (preserveFileName && !isValidFileName(file.name)) return FileValidationError.InvalidFileName
return null
}

/**
* Whether [file] matches any entry in [allowedFileType]. Each entry is a file extension
* (`".pdf"` or `"pdf"`), an exact MIME type (`"application/pdf"`) or a MIME wildcard
* (an `image/` prefix ending in `*`), not extension-only.
* Extension entries are matched against the file's extension; MIME and wildcard entries against
* its resolved content type ([SelectedFile.mimeType], which the picker fills from the extension
* when the provider omits it). A null/unresolved MIME simply can't satisfy a MIME/wildcard entry.
*/
private fun matchesAllowedType(file: SelectedFile, allowedFileType: Array<String>): Boolean {
val ext = file.extension
val mime = file.mimeType?.trim()?.lowercase()
return allowedFileType.any { raw ->
val entry = raw.trim().lowercase()
when {
entry.isEmpty() -> false
entry.endsWith("/*") -> mime != null && mime.startsWith(entry.dropLast(1))
entry.contains('/') -> mime == entry
else -> ext.isNotEmpty() && ext == entry.trimStart('.')
}
}
}
}
53 changes: 53 additions & 0 deletions common/src/main/kotlin/Skyflow/core/file/FileValidationError.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package Skyflow.core.file

/**
* A client-side file validation failure, carrying two message forms:
*
* - [displayMessage] is shown on the element itself and may name the offending file(s).
* - [reportMessage] is what `uploadFiles(...)` hands back to the app and never contains a file name.
*
* Pure and contract-agnostic (no skyvault/flowvault types), so it lives in `common/` beside
* [FileUploadValidator] and can be reused if flowvault adopts file upload.
*/
internal sealed class FileValidationError {
object NoFileSelected : FileValidationError()
object InvalidFileType : FileValidationError()
object InvalidFileSize : FileValidationError()
object InvalidFileName : FileValidationError()
data class FileCountExceeded(val maxCount: Int) : FileValidationError()
data class FileCountAndSizeExceeded(val maxCount: Int, val maxSize: Long) : FileValidationError()
data class FileSizeExceeded(val maxSize: Long, val fileNames: List<String>) : FileValidationError()

/** Always 400 — every client-side file failure is a validation error. */
val code: Int get() = 400

/** Shown on the element. May contain file names; the SDK draws it, the app never reads it. */
val displayMessage: String
get() = when (this) {
is FileSizeExceeded ->
if (fileNames.size > 1)
"${fileNames.joinToString(", ")} exceeds the ${sizeLabel(maxSize)} size limit. " +
"Remove it or choose a smaller file"
else reportMessage
else -> reportMessage
}

/** Returned to the app through `uploadFiles(...)`. Never contains a file name. */
val reportMessage: String
get() = when (this) {
NoFileSelected -> "No File Selected"
InvalidFileType -> "Invalid File Type."
InvalidFileSize -> "Invalid File Size"
InvalidFileName ->
"Invalid File Name. Only alphanumeric characters and !-_.*() are allowed."
is FileCountExceeded ->
"You can upload up to $maxCount files. Remove file(s) to add more"
is FileCountAndSizeExceeded ->
"You can upload up to $maxCount files, each under ${sizeLabel(maxSize)}"
is FileSizeExceeded ->
"File exceeds the ${sizeLabel(maxSize)} size limit. Choose a smaller file"
}
}

/** "32 MB" for a byte count, rounded to whole megabytes (decimal, matching the 32,000,000 cap). */
private fun sizeLabel(bytes: Long): String = "${Math.round(bytes / 1_000_000.0)} MB"
Loading
Loading